Tecram
Tecram

Reputation: 1

React JS + Axios return undefined first

I trying make an axios get from context file into function and call this from component to return data.

Context file:

const getPets = async () => {
await axios.get('http://localhost:1337/api/pets?populate=*')
  .then((res) => {
    return res.data
  })
  .catch(err => {
    console.log(err)
 })}

Component file:

const [pets, setPets] = useState([])

useEffect( () => {
setPets(getPets())},[])

return (console.log(pets))

The return value is undefined and i don't know why. Can we help me please?

Tks!

Upvotes: 0

Views: 76

Answers (1)

Art Bauer
Art Bauer

Reputation: 489

Modify getPets():

const getPets = async () => {
    const res = await axios.get('http://localhost:1337/api/pets? populate=*');
    return res.data;
}

getPets() returns a promise

useEffect(() => {
    getPets().then(res => setPets(res));
}, []);

return (
    <>
        {pets?.map(pet => { /* some JSX */})}   
    </>
);

Upvotes: 2

Related Questions