skip to Main Content

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


  1. it seems that the error might be the fact that you are not passing the income, expense, and error states to the GlobalContext.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:

    <GlobalContext.Provider
      value={{
        income,
        setIncome,
        expense,
        setExpense,
        error,
        setError,
        addIncome
      }}
    >
      {children}
    </GlobalContext.Provider>
    

    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:

    import { useGlobalContext } from './context/globalContext.js';
    
    function MyComponent() {
      const { income, expense, error, addIncome } = useGlobalContext();
    
      // ...
    }
    

    Hope this helps.

    Login or Signup to reply.
  2. Replace axios with fetch api: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

    There 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%22

    As 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search