'error due to usecontext returning undefined value before bringing the correct array
I've built a code at codesandbox so I could display what is going on.
When I uncomment the <p>{chosenPokemon[0].id}</p> line in the aplication run a error: Cannot read properties of undefined (reading 'id'). Here is the file where the problem is going on:
import { usePokemon } from "../../hooks/usePokemon";
export const MapTest = () => {
const { chosenPokemon } = usePokemon("ditto");
console.log(chosenPokemon);
return (
<>
<h1>Map Test</h1>
{/* <p>{chosenPokemon[0].id}</p> */}
</>
);
};
My conclusion is that my context file is bringing a undefined value before bringing the correct one. Here is my context file:
import { createContext, useContext, useState, useEffect } from "react";
import axios from "axios";
const DittoContext = createContext();
export default function DittoProvider({ children }) {
const [ditto, setDitto] = useState();
const api = axios.create({
baseURL: "https://pokeapi.co/api/v2/pokemon"
});
useEffect(() => {
api
.get("/ditto")
.then((response) => setDitto(response.data))
.catch((err) => console.log(err));
}, []);
return (
<DittoContext.Provider value={{ ditto, setDitto }}>
{children}
</DittoContext.Provider>
);
}
export const useDitto = () => {
const context = useContext(DittoContext);
const { ditto, setDitto } = context;
return { ditto, setDitto };
};
How can I fix this error that has been going on?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
