简体   繁体   中英

My state is not updating using React Hooks

I have an event that gets triggered upon change. This event checks which filter has been changed and then updates the state accordingly.

If I was not using react hooks, I would have gone for something like this -

const target = e.target;
const value = e.type === "checkbox" ? target.checked : target.value;
const name = e.target.name;    
this.setState({ [name]: value });

As you can see I would be able to update the state name using the [name] but since I am using react hooks I am not able to use the above. Instead I have got this -

  const [type, setType] = useState("all");
  const [capacity, setCapacity] = useState(1);
  const [price, setPrice] = useState(0);
  const [minPrice, setMinPrice] = useState(0);
  const [maxPrice, setMaxPrice] = useState(0);
  const [minSize, setMinSize] = useState(0);
  const [maxSize, setMaxSize] = useState(0);

  const handleChange = (e) => {
    const target = e.target;
    const value = e.type === "checkbox" ? target.checked : target.value;
    const name = e.target.name;
    
    switch (name) {
      case "type":
        setType(value);
        break;
      case "capacity":
        setCapacity(value);
        break;
      case "price":
        setPrice(value);
        break;
      case "minPrice":
        setMinPrice(value);
        break;
      case "maxPrice":
        setMaxPrice(value);
        break;
      case "minSize":
        setMinSize(value);
        break;
      case "maxSize":
        setMaxSize(value);
        break;
      default:
        return;
    }
  };

What you have seen above does not work for some reason. When I trigger the filter it goes into the case as I have already tested this, but the state does not seem to update. The name and value have also been logged and they are fine too. I am not sure what is causing this and I am only new to programming so any help would be appreciated!

*** Just to reiterate the value and name are both working and so is the switch statement. It's just the state that is not updating ***

Welcome to SO. You can still write similar code to this.setState example you provided with useState. Here's a quick runnable example.

An answer focused around your project:

  1. Create a component that uses useContext and just load the values you need and the handleChange method
const Test = () => {
  const { type, capacity, handleChange } = React.useContext(RoomContext);

  console.log(type, capacity);

  return (
      <div>
        <select name="type" onChange={handleChange}>
            <option value="all">all</option>
            <option value="another">another</option>
            <option value="one">one</option>
        </select>
        <select name="capacity" onChange={handleChange}>
          <option value="1">1</option>
          <option value="50">50</option>
          <option value="100">100</option>
        </select>
      </div>
  )
};
  1. Add the Test component as a child of the Room Provider.
  2. Start the app and you should see it will update as normal

Working runnable examples:

const target = e.target;
const value = e.type === "checkbox" ? target.checked : target.value;
const name = e.target.name;    
this.setState({ [name]: value });

 const rootEl = document.getElementById('root'); const App = () => { const [form, setForm] = React.useState({ name: '', checkbox: false, }); const handleChange = (e) => { const target = e.target; const value = e.type === "checkbox"? target.checked: target.value; const name = e.target.name; setForm(prevState => ({...prevState, [name]: value })); } return ( <div> <label>Name</label> <input type="text" name="name" value={form.name} onChange={handleChange} /> <label>Checkbox</label> <input type="checkbox" name="checkbox" checked={form.checkbox} onChange={handleChange} /> <pre>{JSON.stringify(form)}</pre> </div> ) } ReactDOM.render(<App />, rootEl);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script> <div id="root"></div>

Here's a running example of the code with multiple useStates.

 const rootEl = document.getElementById('root'); const App = () => { const [name, setName] = React.useState(''); const [checkbox, setCheckbox] = React.useState(false); const handleChange = (e) => { const target = e.target; const value = e.type === "checkbox"? target.checked: target.value; const name = e.target.name; switch (name) { case "name": setName(value); break; case "checkbox": setCheckbox(value); break; default: return; } }; return ( <div> <label>Name</label> <input type="text" name="name" value={name} onChange={handleChange} /> <label>Checkbox</label> <input type="checkbox" name="checkbox" checked={checkbox} onChange={handleChange} /> <pre>{JSON.stringify({ name, checkbox })}</pre> </div> ) } ReactDOM.render(<App />, rootEl);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script> <div id="root"></div>

The fix to my issue was that it was not re-rendering so it was a cycle behind the whole time.

Adding the state as a dependancy in the useEffect fixes the problems, I hope this helps anyone else having a similar issue. would be great to help the community in one way or another.

import React, { createContext, useState, useEffect } from "react";

import items from "../data";

export const RoomContext = createContext();

const RoomProvider = (props) => {
  const [rooms, setRooms] = useState([]);
  const [sortedRooms, setSortedRooms] = useState([]);
  const [featuredRooms, setFeaturedRooms] = useState([]);
  const [loading, setLoading] = useState(true);
  const [type, setType] = useState("all");
  const [capacity, setCapacity] = useState(1);
  const [price, setPrice] = useState(0);
  const [minPrice, setMinPrice] = useState(0);
  const [maxPrice, setMaxPrice] = useState(0);
  const [minSize, setMinSize] = useState(0);
  const [maxSize, setMaxSize] = useState(0);
  const [breakfast, setBreakfast] = useState(false);
  const [pets, setPets] = useState(false);

  //call the formatted data
  useEffect(() => {
    //set rooms
    const rooms = formatData(items);
    //set the featured rooms
    const featuredRooms = rooms.filter((room) => room.featured === true);
    //always show the max price as default
    const maxPrice = Math.max(...rooms.map((item) => item.price));
    //always show the max price as default
    const maxSize = Math.max(...rooms.map((item) => item.size));

    setRooms(rooms);
    setSortedRooms(rooms);
    setFeaturedRooms(featuredRooms);
    setLoading(false);
    setMaxPrice(maxPrice);
    setMaxSize(maxSize);
    setPrice(maxPrice);
  }, [
    type,
    capacity,
    price,
    minPrice,
    maxPrice,
    minSize,
    maxSize,
    breakfast,
    pets,
  ]);

  //format data is getting all the required fields we want to pull from the originl data
  const formatData = (items) => {
    let tempItems = items.map((item) => {
      const id = item.sys.id;
      const images = item.fields.images.map((image) => image.fields.file.url);

      const room = { ...item.fields, images: images, id: id };
      return room;
    });
    return tempItems;
  };

  const getRoom = (slug) => {
    let tempRooms = [...rooms];
    const room = tempRooms.find((room) => room.slug === slug);
    return room;
  };

  const handleChange = (e) => {
    const target = e.target;
    const value = e.type === "checkbox" ? target.checked : target.value;
    const name = e.target.name;

    switch (name) {
      case "type":
        setType(value);
        break;
      case "capacity":
        setCapacity(value);
        break;
      case "price":
        setPrice(value);
        break;
      case "minPrice":
        setMinPrice(value);
        break;
      case "maxPrice":
        setMaxPrice(value);
        break;
      case "minSize":
        setMinSize(value);
        break;
      case "maxSize":
        setMaxSize(value);
        break;
      case "breakfast":
        setBreakfast(value);
        break;
      case "pets":
        setPets(value);
        break;
      default:
        return;
    }
    console.log(name, value);
  };

  const filteredRooms = () => {
    let initialRooms = [...rooms];

    if (type !== "all") {
      initialRooms = initialRooms.filter((room) => room.type === type);
    }
    console.log("room type is", type);
    setSortedRooms(initialRooms);
  };

  return (
    <RoomContext.Provider
      value={{
        rooms,
        featuredRooms,
        getRoom,
        loading,
        sortedRooms,
        type,
        capacity,
        price,
        minPrice,
        maxPrice,
        minSize,
        maxSize,
        breakfast,
        pets,
        handleChange,
        filteredRooms,
      }}
    >
      {props.children}
    </RoomContext.Provider>
  );
};

export default RoomProvider;

did you import useState?

import React, {useState} from 'react';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM