DevCo
DevCo

Reputation: 479

React Hooks State with preserving previous state (REACT DND)

I am trying dynamic setState using useState to an object.

const [check, setcheck] = useState({
    q1:'',
    q2:''
})

but I am failing to preserve the last state. I am using react dnd whenever I start dragging, it clear "State". I am not sure if its rendering or what or I am doing something wrong. I have an option to set the state to localStorage but Can someOne please review my code block I will be thankful.

following is my code

import React, { useState, useEffect } from "react";
import { useDrag } from "react-dnd";
import ItemTypes from "./ItemTypes";
const style = {..}
const ItemBox = ({ url, id, idref }) => {
  const [check, setcheck] = useState({
    q1: "",
    q2: ""
  });

  console.log(check, "CheckState");
  useEffect(() => {
    idref.current = { check };
  }, [check, idref]);
  const [{ isDragging }, drag] = useDrag({
    item: { id, type: ItemTypes.BOX },
    end: (item, monitor) => {
      const dropResult = monitor.getDropResult();
      if (item && dropResult) {

        // * here I am trying to set the state *

        setcheck({ ...check, [item.id]: dropResult.id });
      }
    },
    collect: monitor => ({
      isDragging: monitor.isDragging()
    })
  });

  const opacity = isDragging ? 0.4 : 1;
  return (
    <div
      id={id}
      ref={drag}
      style={{ ...style, opacity, backgroundImage: `url(${url})` }}
    />
  );
};
export default ItemBox;

Upvotes: 0

Views: 936

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196051

You should use the callback version of the setcheck becuase useDrag caches the options you pass so check refers to the first time check.

setcheck((currentCheck) => ({ ...currentCheck, [item.id]: dropResult.id }));

Upvotes: 2

Related Questions