'Promise async/await is not working - array not updated

I am updating an array addItems as soon a checkbox is clicked, using action/reducer and dispatch but when I check the array it is not up to date. to resolve this I have introduced async/await promises (I am new to promises) but when I check in then the array is still not updated! What am I missing?

const [addItems, dispatch] = useReducer((state, action) => {
switch (action.type) {
  case "add":
    return [
      ...state,
      {
        id: state.length,
        data: action.data
      }
    ];
  default:
    return state;
}
}, []);

const callDispatch = (sampleId, testId, checked) => {
      console.log("sample: " + sampleId + " t: " + testId + " bool: " + checked);          

      const linkedData = {
        sampleId: sampleId,
        TestId: testId,
        isSelected: checked
      };
  
      return Promise.resolve(
      dispatch({
        type: "add",
        data: linkedData
      }));
    };

const linkDataHandler = async(samplesData, test, e) => {
    
    const isSelected =  e.target.checked;

    await callDispatch(samplesData.id, test.testList.id, isSelected) 
    .then( r =>{
        //addItems is still not updated when checked here
    }})
    .catch(error => console.log(error));

 <input
    type="checkbox"
    onClick={(e) => {
      linkDataHandler(sampleObj, testObj, e);
    }}
  />

A working sample: https://codesandbox.io/s/staging-moon-xv1ku5?file=/src/App.js

Sol1: Tried using Callback as follows but didnot work

import React, { useReducer, useEffect, useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import { useRef } from "react";

export default function App() {
const [addItems, dispatch] = useReducer((state, action) => {
switch (action.type) {
  case "add":
    return [
      ...state,
      {
        id: state.length,
        data: action.data
      }
    ];
  default:
    return state;
 }
 }, []);

  const linkDataHandler = (samplesData, test, e) => {
  const isSelected = e.target.checked;
  console.log(isSelected);
  callDispatch(samplesData, test, isSelected, (user) => {
  console.log(addItems);
  });
};
const callDispatch = (sampleId, testId, checked, callback) => {
const linkedData = {
  sampleId: sampleId,
  TestId: testId,
  isSelected: checked
};

callback(
  dispatch({
    type: "add",
    data: linkedData
  })
);
};

return (
<div className="App">
  <h1>Hello CodeSandbox</h1>
  <input
    type="checkbox"
    onClick={(e) => {
      linkDataHandler(1, 1, e);
    }}
  />
  ABC
</div>
);
}

Sol2: tried adding useeffect

useEffect(() => {
console.log(addItems.length);
  }, addItems);

The final argument passed to useEffect changed size between renders. The order and size of this array must remain constant.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source