alberto_g
alberto_g

Reputation: 39

useContext returning an empty object in Gatsby application

When using useContext() I'm getting an empty object.

I created a file that contains my Context, Provider, and Consumer

src/utils/notesContext.js

import PropTypes from "prop-types"
import React, { createContext, useState } from "react"

export const Context = createContext({})

export const Provider = props => {
  const {
    notes: initialNotes,
    selectedNote: initialSelectedNotes,
    children,
  } = props

  const [notes, setNotes] = useState([[""]])
  const [selectedNote, setSelectedNote] = useState([[""]])

  const addNewNote = note => {
    console.log(note)
  }

  const notesContext = {
    notes,
    setNotes,
    selectedNote,
    setSelectedNote,
    addNewNote,
  }

  return <Context.Provider value={notesContext}>{children}</Context.Provider>
}

export const { Consumer } = Context

Provider.propTypes = {
  notes: PropTypes.array,
  selectedNote: PropTypes.object,
}

Provider.defaultProps = {
  notes: [],
  selectedNote: {},
}

Then within my index file, I have the following

src/pages/index.js

import React, { useContext } from "react"
import { Context } from "../utils/notesContext"

const Index = ({ data, location }) => {
  const initNote = data.note

  const notesContext = useContext(Context) // notesContext is empty
  const { notes, selectedNote, setSelectedNote, addNewNote } = notesContext
  addNewNote(initNote)
...
}

Did I set up something incorrectly with my context or provider? Another thing worth mentioning is that this is in a Gatsby application so not sure if this could be causing an underlying issue that I'm not aware of.

Thanks in advance!

Upvotes: 0

Views: 1317

Answers (1)

bertdida
bertdida

Reputation: 5288

Your Index component should be used inside notesContext Provider.

Read more about Context.Provider.

import { Context, Provider } from "./notesContext";

const Index = () => {
  const notesContext = useContext(Context);
  console.log(notesContext); // now this is not an empty object

  return <p>Index</p>;
};

export default function App() {
  // notice here, we're wrapping Index inside our Provider
  return (
    <Provider>
      <Index />
    </Provider>
  );
}

Edit sweet-goodall-pnsx0

Upvotes: 1

Related Questions