0

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!

1 Answer 1

2

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 */})}   
    </>
);
Sign up to request clarification or add additional context in comments.

16 Comments

Thaks for your answer. I try this and still returns undefined in component file return.
That is because you are returning the result of the function call return (console.log(pets)) -- it writes pets into the console, but returns undefined. You might want return pets;. In this case the component will return twice (since useEffect is async). To prevent that you might also want to use useLayoutEffect() instead, but ususally it is not necessary
Ok, i undertand. But in return i need execute a map function to render data and still doesn't work. Sorry.
Modified my answer. Please check
Into the return of component i have this: {pets.map((pet, index) => (console.log(pet)))} and in browser give me this error: Uncaught TypeError: Cannot read properties of undefined (reading 'map')
|

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.