Home > Back-end >  Trying to put axios data in a variable with a return function, not working (React)
Trying to put axios data in a variable with a return function, not working (React)

Time:11-07

    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.

CodePudding user response:

Because you are not returning anything from your stepTwo function.

CodePudding user response:

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.

  • Related