0

I think it is weird, but I do not understand why useState does not being set to new value. When looking at the picture we could see useSelector is updated and it should update useState aswell. I'm talking about flatData state. From what I understand flatData`` should get currentColivingdata at the first render. Then, whenevercurrentColivingis updated -flatData``` should be updated. However, the picture says different story. Here is the code:

function FlatInformation() {
  const currentColiving = useSelector(selectCurrentColiving);
  const [imageFiles, setImageFiles] = useState([]);
  const [flatData, setFlatData] = useState({
    name: currentColiving?.title || "",
    description: currentColiving?.description || "",
    photos: currentColiving?.imageUrl || [],
    amenities: currentColiving?.amenities || [],
  });
  // Boolean whether a person can edit coliving settings or not.
  const flatSettingsEditMode = useSelector(selectIsInSettingsEditMode);

  useEffect(() => {
    if (currentColiving) {
      console.log(flatData, 'flatData-begin');
      setFlatData((prevState) => ({
        name: currentColiving.title,
        description: currentColiving.description,
        photos: currentColiving.imageUrl,
        amenities: currentColiving.amenities,
      }));
      console.log(currentColiving);
      console.log(flatData, 'Flatdata-end');
    }
  }, [currentColiving]);

  useEffect(() => {
    console.log(flatData, "flatData");
  }, [flatData]);
return (
<div>ommited</div>)

}

Pictures: enter image description here

Mantofka
  • 206
  • 1
  • 12
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Emile Bergeron Apr 12 '22 at 17:36
  • 1
    Also, it looks like `currentColiving` is an array, but you're accessing properties on it like it's an object. – Emile Bergeron Apr 12 '22 at 17:41
  • 1
    @EmileBergeron Yuup you are totally correct. Everything now is working properly. I updated ```currentColiving``` with ```.filter()```, so it returned me an array, but I need only ```[0]```. Thank you :) – Mantofka Apr 12 '22 at 17:45

0 Answers0