简体   繁体   中英

React clean up function when setting context via hook api

I have a context set through react hooks. The initial state looks like:

const initialState = {
    allTasks: [],
    tasksToAuth: [],
    pendingTasks: [],
    completedTasks: [],
    users: [],
    headers: headers,
    categories: categories
};

When trying to set the first five attributes through an api, it causes an error "Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function."

My code calling the api sits in a useEffect hook.

React.useEffect(() => {
    async function getItems() {
        try {
            await actions.setAllTasks();
            await actions.setUsers();
            await actions.setUserPendingTasks();
            await actions.setTasksToAuth();
            await actions.setUserCompletedTasks();
        } catch (e) {
            alert("Error hit ", e);
            console.log(e);
        }
    }

    getItems();
}, [actions]);

My actions and middleware / reducer is as follows:

Actions.js

setAllTasks: tasks => dispatch({ type: "admin.set.all.tasks", payload: tasks }),

setTasksToAuth: tasks => dispatch({ type: "admin.set.submitted", payload: tasks }),

setUserPendingTasks: tasks => dispatch({ type: "admin.set.pending", payload: tasks }),

setUserCompletedTasks: tasks => dispatch({ type: "admin.set.completed", payload: tasks }),

setUsers: tasks => dispatch({ type: "admin.set.users", payload: tasks }),

Middleware.js

switch (action.type) {
    case "admin.set.all.tasks":
        axios
            .get("http://localhost:3001/api/admin/tasks")
            .then(res => {
                console.log(res);
                dispatch({ type: action.type, payload: res.data.data });
            })
            .catch(e => console.log(e));
        break;

    case "admin.set.pending":
        axios
            .get("http://localhost:3001/api/admin/tasks/pending")
            .then(res => {
                console.log(res.data.data);
                dispatch({ type: action.type, payload: res.data.data });
            })
            .catch(e => console.log(e));
        break;

    case "admin.set.submitted":
        axios
            .get("http://localhost:3001/api/admin/tasks/submitted")
            .then(res => {
                console.log(res.data.data);
                dispatch({ type: action.type, payload: res.data.data });
            })
            .catch(e => console.log(e));
        break;

    case "admin.set.completed":
        axios
            .get("http://localhost:3001/api/admin/tasks/completed")
            .then(res => {
                console.log(res.data.data);
                dispatch({ type: action.type, payload: res.data.data });
            })
            .catch(e => console.log(e));
        break;

    case "admin.set.users":
        axios
            .get("http://localhost:3001/api/admin/users/")
            .then(res => {
                console.log(res);
                dispatch({ type: action.type, payload: res.data.data });
            })
            .catch(e => console.log(e));
        break;

Finally, reducer.js

case "admin.set.all.tasks":
    console.log("admin.set.all.tasks");
    return { ...state, allTasks: action.payload };

case "admin.set.pending":
    console.log("admin.set.pending");
    return mapPendingTasks(state, action.payload);

case "admin.set.submitted":
    console.log("admin.set.submitted");
    return mapSubmittedTasks(state, action.payload);

case "admin.set.completed":
    console.log("admin.set.completed");
    return mapCompletedTasks(state, action.payload);

case "admin.set.users":
    console.log("admin.set.users");
    return { ...state, users: action.payload };

It would seem the error occurs in here - " TypeError: Unable to set property 'uin' of undefined or null reference"

So as far as I can tell, the state of allTasks is not set correctly first to create the task object first below?

An example of the returned functions in reducer.js is:

function mapCompletedTasks(state, payload) {
    let tasks = [];
    payload.forEach(element => {
        let task = state.allTasks.filter(e => e.id === element.task_id)[0];
        task.uin = element.uin;
        task.status = element.status;
        task.due_by = element.due_by;
        task.submitted_on = element.submitted_on;
        task.completed_on = element.completed_on;
        tasks.push(task);
    });
    return { ...state, completedTasks: tasks };
}

How can I solve this problem? I have seen about cleanup in React useEffect like

return () => cleanup();

But I am not sure how to implement. Thanks

EDIT: Better formatting of code EDIT2: Added another error seen

As commented; you can use useIsMounted , although I would not yarn/npm install it and instead just add it to your code in lib or something:

export default function CountersContainer() {
  const [val, setVal] = useState([1]);
  useEffect(() => {
    //cause all items to unmount in half a second
    setTimeout(() => setVal([]), 500);
  });
  return (
    <div>
      {val.map(val => (
        <Item val={val} key={val} />
      ))}
    </div>
  );
}
//item will be unmounted in half a second
const Item = ({ val }) => {
  const isMounted = useIsMounted();
  const set = useState()[1];
  useEffect(() => {
    //trying to do a set state after Item is unmounted
    setTimeout(() => {
      //luckily it'll check if it's mounted
      if (isMounted.current) {
        set(22);
      }
    }, 700);
  }, [isMounted, set]);
  return <div>{val}</div>;
};

const useIsMounted = () => {
  const isMounted = useRef(false);
  useEffect(() => {
    isMounted.current = true;
    return () => (isMounted.current = false);
  }, []);
  return isMounted;
};

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