Im trying to build a simple app in react but i need to fetch an api to get the data and I'm using React context so i don't need to pass a bunch of props to the components. But sometimes I need to split a string that comes from the api and beacause of the fetch sometimes im triying to split an undefined value so I get an error. How can I solve this? An example of what I'm doing is somethin like this:
export const MyContext = createContext()
export const MyContextProvider = (props) => {
const [data, setData] = useState({})
const apiUrl = 'some api url'
useEffect(() => {
fetch(apiUrl)
.then(res => res.json())
.then(resData => setData(resData))
.catch(err => console.error(err))
}, [apiUrl]) // the dependencies because I use more states that modified the apiUrl
return (
data ?
<MyContext.Provider
value = {{data}}
>
{props.children}
</MyContext.Provider>
: <div></div>
)
}
then when I tried to do:
data.someKey.split('some regex')
I got the error, but I don't know how to solve this
You're performing an asynchronous request, and your initial state is an empty object, if you try to console log this !!{}
console.log(!!{}) // prints true because an empty object is a truthy value
So basically in your render, data is always returning true even though your request has not finished and there's a moment when your code will try to access someKey and it will be undefined because it doesn't exist at the time, you need to add some logic and make the data value falsey at the beginning, I would suggest to make your initial state null.
const [data, setData] = useState(null);
That will make the condition be false at the beginning of the request and if everything succeed you should have an object with the correct keys.
I also suggest to verify if the key exists before trying to split it
data.someKey ? data.someKey.split('some regex') : ''