-1

I have set 2 arrays with useState in 2 different files:

const [filterQuery, setFilterQuery] = React.useState({
        instructor: [],
        material: [],
    })
const [query, setQuery] = React.useState({
    instructor: [],
    material: [],
  })

And i have this function that will update query with values from filterQuery:

const applyFilter = (filterQuery) => {
    setQuery((prev) => ({
      ...prev,
      instructor: filterQuery.instructor,
      material: filterQuery.material,
    }));
  }

The strange behavior is when i call setFilterQuery from a different function, an example is updating filterQuery when a button is clicked

onClick = (value) => {
   setFilterQuery({
     ...filterQuery,
     instructor: value
   })
}

What I expected is it will just update filterQuery, but query will magically updated with filterQuery too whereas it has no connection to the function whatsoever.

What could trigger this ? I have tried a few things, declaring a new variable first before using the setQuery :

const filter = filterQuery;
setQuery((prev) => ({
      ...prev,
      instructor: filter.instructor,
      material: filter.material,
    }));

not working. I have also tried changing the set format without the prev, using just ...query or without them and still not working.

Thank you for reading, helps appreciated.. Will provide more code info / what else I have tried if asked.

1 Answers1

0

In JavaScript primitive types are passed around as values: meaning that each time a value is assigned, a copy of that value is created.

On the other side objects (including plain objects, array, functions, class instances) are references. If you modify the object, then all variables that reference that object are going to see the change.

Here what basically happens is that you are passing the reference of query to filterQuery, not the value to query that's why when you change either query or filterQuery they both get updated. You can see more details and examples at this question's answer and difference between values and reference