Home > Software engineering >  react useContext setState is not a function
react useContext setState is not a function

Time:10-22

I'm working on a react app and I need to keep an array of names in my global state like on this file:

import React from "react";
import { useState } from "react";

const initialState = {
  nameList: [],
  test: 'hello'
}

export const Context = React.createContext()

const Data = ({ children }) => {
  const [state, setState] = useState(initialState)

  return(
    <Context.Provider value={[state, setState]}>
      {children}
    </Context.Provider>
  )
}

export default Data

However, when I try to set "nameList" to a new value in this other file:

const [state, setState] = useContext(Context);
const [currName, setCurrName] = useState('');

const handleAddName = () => {
  setState.nameList(prevState => [...prevState, currName])
}

I get a "setState.nameList is not a funtion" error and I can't find nor understand the reason why, any help would be much appreciated

CodePudding user response:

You're updating the state incorrectly, here's how to do it in your case:

const handleAddName = () => {
    setState(prevState => ({
        ...prevState,
        nameList: [...prevState.nameList, currName]
    }))
}

This will make sure that the state is updated immutably.

setState.nameList is wrong because setState is a function but not an object that will magically have the keys of your state.

  • Related