0
    import React from "react";
import ReactDOM from "react-dom";
import { createRoot } from 'react-dom/client';
import axios from "axios";

const BASEURL = "https://jsonplaceholder.typicode.com/users";


function axiosTest() {
    return axios.get(BASEURL).then(response => response.data)
}


function stepTwo(){
axiosTest()
        .then(data =>{
           
           var namesArray = data;
           //console.log(namesArray);
          return namesArray;
        })
    }

function Component1(){

var array2map = stepTwo();

console.log(array2map);
return(
    <div>
    {array2map.map(item => <p>item.name</p>)}
        </div>
    )


}




const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Component1 />);

Why does array2map come back as undefined? That's what it says in the console log and what it says in the error I get as the result of trying to map something undefined. That's my question, I don't know how much more verbose about it I can be, but this site is forcing me to write more.

2 Answers 2

1

Because you are not returning anything from your stepTwo function.

Sign up to request clarification or add additional context in comments.

2 Comments

So what does the return statement belong to?
@DennisM to the then callback.
1

Two things should be noted here:

Firstly, stepTwo does not return anything, the return statement it contains is for the then callback. The callback is run after stepTwo returns undefined.

Secondly, anything in a function component's top-level, like the var array2Map = stepTwo() is run before the component is mounted. Whereas fetch calls like axios should be made after the component has mounted.

Here's a solution.

async function axiosTest() {
    var response = await axios.get(BASEURL);
    return response.data;
}

async function stepTwo() {
    let data = await axiosTest();
    return data;
}

class Component1 extends Component {

    constructor(props) {
        super(props);
        this.state = {array2Map: []};
    }

    async componentDidMount() {
        this.setState({array2Map: stepTwo()});
    }

Important advice: naming is very important in programming. Give appropriate names to your variables, methods & components. stepTwo doesn't do anything, that axiosTest already does. The latter can be used directly. I guess your axios call, returns a list of names. In that case, you can use names instead of array2Map.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.