here the code
index.js :
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
import GlobalStyle from './styles/GlobalStyle.js'
import { GlobalProvider } from './context/globalContext.js';
ReactDOM.render(
<React.Fragment>
<GlobalStyle />
<GlobalProvider>
<App />
</GlobalProvider>
</React.Fragment>,
document.getElementById('root')
);
here a globalContext.js
import React, { useContext, useState } from 'react'
import axios from 'axios'
const BASE_URL = "http://localhost:5000/"
const GlobalContext = React.createContext()
export const GlobalProvider = ({ children }) => {
const [income, setIncome] = useState([])
const [expense, setExpense] = useState([])
const [error, setError] = useState(null)
const addIncome = async (income) => {
const response = await axios.post(`${BASE_URL}income`)
.catch((err) => {
setError(err.response.body.message)
})
}
return (
<GlobalContext.Provider
value={`hello`}
>
{children}
</GlobalContext.Provider>
)
}
export const useGlobalContext = () => {
return useContext(GlobalContext)
}
Why is it that when I include the component, it can’t be rendered?
I’m not sure why, and there are no error messages either.
i want it rendered like before
2
Answers
it seems that the error might be the fact that you are not passing the
income
,expense
, and error states to theGlobalContext.Provider
component. You can try updating the value prop of the `GlobalContext.Provider´ to an object that contains these states and the ´addIncome´ function. Like this:Then, in your App component or any other component that needs these states and functions, you can use the
useGlobalContext
hook to consume the context:Hope this helps.
Replace
axios
withfetch
api: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_APIThere are already a few reported cases of this issue in
axios
repo: https://github.com/axios/axios/issues?q=is%3Aissue+%22Cannot+use+import+statement%22As long as your use-cases are simple, you can use
fetch
.fetch
comes in all browsers, and as such, you dont have to install any package to use it.