React useState hook affecting default variable used in state regardless spread operators, Object.assign and etc

Malkhazi Dartsmelidze

I am experienced js/React developer but came across case that I can't solve and I don't have idea how to fix it.

I have one context provider with many different state, but one state looks like following:

const defaultParams = {
  ordering: 'price_asc',
  page: 1,
  perPage: 15,
  attrs: {},
}

const InnerPageContext = createContext()

export const InnerPageContextProvider = ({ children }) => {
  const [params, setParams] = useState({ ...defaultParams })

  const clearParams = () => {
    setParams({...defaultParams})
  }

  console.log(defaultParams)

  return (
    <InnerPageContext.Provider
      value={{
        params: params,
        setParam: setParam,
        clearParams:clearParams
      }}
    >
      {children}
    </InnerPageContext.Provider>
  )
}

I have one button on page, which calls clearParams function and it should reset params to default value. But it does not works

Even when i console.log(defaultParams) on every provider rerendering, it seems that defaultParams variable is also changing when state changes

I don't think it's normal because I have used {...defaultParams} and it should create new variable and then pass it to useState hook.

I have tried:

const [params, setParams] = useState(Object.assign({}, defaultParams))
const clearParams = () => {
  setParams(Object.assign({}, defaultParams))
}
const [params, setParams] = useState(defaultParams)
const clearParams = () => {
  setParams(defaultParams)
}
const [params, setParams] = useState(defaultParams)
const clearParams = () => {
  setParams({
    ordering: 'price_asc',
    page: 1,
    perPage: 15,
    attrs: {},
  })
}

None of above method works but 3-rd where I hard-coded same object as defaultParams. The idea is to save dafult params somewhere and when user clears params restore to it. Do you guys have some idea hot to make that?

Edit: This is how I update my params:

const setParam = (key, value, type = null) => {
    setParams(old => {
      if (type) {
        old[type][key] = value
      } else old[key] = value
      console.log('Params', old)
      return { ...old }
    })
  }
VasilyRogoja

please show how you update the "params".

if there is something like this in the code "params.attrs.test = true" then defaultParams will be changed

if old[type] is not a simple type, it stores a reference to the same object in defaultParams. defaultParams.attrs === params.attrs. Since during initialization you destructuring an object but not its nested objects.

the problem is here: old[type][key] = value

solution:

const setParam = (key, value, type = null) => {
    setParams(old => {
      if (type) {
        old[type] = {
          ...old[type],
          key: value,
        }
      } else old[key] = value
      return { ...old }
    })
  }

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

create custom hook to override useState() hook and merge object properties (React JS)

分類Dev

React trying to assign props to state variable doesn't work

分類Dev

Assign object to a variable before exporting as module default warning

分類Dev

Adding a key-value pair to an object inside loop using React useState hook

分類Dev

React Hooks: useState updater function: Why does this hook remove the object upon drag?

分類Dev

React Hooks useState()with Object

分類Dev

ReactJS - prevState in the new useState React hook?

分類Dev

React UseState hook causing infinite loop

分類Dev

React-hook-form on submit and useState issue

分類Dev

Why is useImperitaveHandle hook used in React?

分類Dev

Cannot set object state after set attempt useState react native maps

分類Dev

Have to click twice to update state (useState hook) with onClick event

分類Dev

Assign Promise To Variable In React

分類Dev

Why does my WebSocket message handler always get React state hook variable's initial value?

分類Dev

React hooks: get state of useState inside a listener

分類Dev

Update state of multiple checkboxes in React with useState

分類Dev

React useState broken? state is not updated correctly

分類Dev

Mocking react-router-dom for useHistory hook causes the following error - TS2698: Spread types may only be created from object types

分類Dev

How to ensure state is not stale in React hook

分類Dev

React useState with Typescript for setting a nested typed object

分類Dev

useState hook - state gets lost i.e. resets to initial value

分類Dev

assign json object to javascript variable in CanvasJS

分類Dev

How to render a React Hook State whose type is an Array of Objects?

分類Dev

React / ReduxでObject.assignまたはSpreadオペレーターを使用しますか?どちらが良い習慣ですか

分類Dev

React Hook useStateがconstを使用し、letしない理由

分類Dev

送信およびuseStateの問題に関するReact-hook-form

分類Dev

How to push an array to state in React? Getting "Invalid attempt to spread non-iterable instance"

分類Dev

Array is not being updated in useState hook?

分類Dev

React update state variable with JSON data

Related 関連記事

  1. 1

    create custom hook to override useState() hook and merge object properties (React JS)

  2. 2

    React trying to assign props to state variable doesn't work

  3. 3

    Assign object to a variable before exporting as module default warning

  4. 4

    Adding a key-value pair to an object inside loop using React useState hook

  5. 5

    React Hooks: useState updater function: Why does this hook remove the object upon drag?

  6. 6

    React Hooks useState()with Object

  7. 7

    ReactJS - prevState in the new useState React hook?

  8. 8

    React UseState hook causing infinite loop

  9. 9

    React-hook-form on submit and useState issue

  10. 10

    Why is useImperitaveHandle hook used in React?

  11. 11

    Cannot set object state after set attempt useState react native maps

  12. 12

    Have to click twice to update state (useState hook) with onClick event

  13. 13

    Assign Promise To Variable In React

  14. 14

    Why does my WebSocket message handler always get React state hook variable's initial value?

  15. 15

    React hooks: get state of useState inside a listener

  16. 16

    Update state of multiple checkboxes in React with useState

  17. 17

    React useState broken? state is not updated correctly

  18. 18

    Mocking react-router-dom for useHistory hook causes the following error - TS2698: Spread types may only be created from object types

  19. 19

    How to ensure state is not stale in React hook

  20. 20

    React useState with Typescript for setting a nested typed object

  21. 21

    useState hook - state gets lost i.e. resets to initial value

  22. 22

    assign json object to javascript variable in CanvasJS

  23. 23

    How to render a React Hook State whose type is an Array of Objects?

  24. 24

    React / ReduxでObject.assignまたはSpreadオペレーターを使用しますか?どちらが良い習慣ですか

  25. 25

    React Hook useStateがconstを使用し、letしない理由

  26. 26

    送信およびuseStateの問題に関するReact-hook-form

  27. 27

    How to push an array to state in React? Getting "Invalid attempt to spread non-iterable instance"

  28. 28

    Array is not being updated in useState hook?

  29. 29

    React update state variable with JSON data

ホットタグ

アーカイブ