Dmitriy
Dmitriy

Reputation: 4503

How to use context react correctly?

There is a code

correct import import App from './components/app/app' (imports are not always saved)

Context

import React from 'react'
export const DataContext = React.createContext({})

App component

import { useEffect, useState, useContext } from 'react'
import Products from '../products/products'
import { DataContext } from '../../services/appContext.js';


const App = () => {
  const { data, setData } = useContext(DataContext)
  const [loading, setLoading] = useState(false)
  const [loaded, setLoaded] = useState(false)
  const [hasError, setHasError] = useState(false)

  const getData = () => {
    setLoading(true)

    fetch('../../services/data.json')
      .then((response) => {
        if (response.ok) {          
          return response.json()
        } else {
          throw new Error('Something went wrong')
        }
      })
      .then((json) => {
        setData(json.data)        
        
        setLoaded(true)
        setLoading(false)        
      })
      .catch(() => {        
        setHasError(true)
        setLoaded(false)
      })
      .finally(() => {
        setLoading(false)
      });
  }

  useEffect(() => {
    getData()
  }, [])

  return (
    <>
      {hasError && !loading && !loaded && (<div>Error</div>)}
        {loading && !hasError && !loaded && (<div>Loading</div>)}
        {loaded && !hasError && !loading && (
          <DataContext.Provider value={{ data, setData }}>
              <Products />
          </DataContext.Provider>
        )}
    </>
  )
}

export default App;

I'm trying to display products using context, but alas, it doesn't work right now.

Explain what am I doing wrong? Thanks in advance.

Upvotes: 0

Views: 177

Answers (1)

yondu_udanta
yondu_udanta

Reputation: 807

there are a couple of things going wrong in your code. I have forked your sandbox and edited the code to correct them.

  1. JSON path in fetch, the path will change wrt to the bundled JS file. So, instead, you can consider importing it and webpack will take care of importing it rightly.

  2. You are passing 'data' as prop to Product Component and trying to access the data using context in Product.

Please check the corrected and working code, here

Upvotes: 1

Related Questions