'React async/await usage - Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'then')
I am adding data to an addItem array using reducers.
I want to wait until the item is actually added before going forward..I have implemented it as follows
const [addItems, dispatch] = useReducer((state, action) => {
switch (action.type) {
case 'add':
return [
...state,
{
id: state.length,
data: action.data
}
];
default:
return state;
}
}, []);
const linkDataHandler = async(samplesData, test, e) => {
const isSelected = e.target.checked;
await callDispatch(samplesData.id, test.testList.id, isSelected)
.then( r =>{
//do something
}});
};
const callDispatch = (sampleId, testId, checked) => {
const linkedData = {
sampleId: sampleId,
TestId: testId,
isSelected: checked
};
dispatch({
type: "add",
data: linkedData
});
};
function linkDataHandler is called on a checkbox onChange() event.
It is giving me
Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'then')
Solution 1:[1]
I have re-written callDispatch as follows. Since it is expected to return a promise
const callDispatch = (sampleId, testId, checked) => {
const linkedData = {
sampleId: sampleId,
TestId: testId,
isSelected: checked
};
return Promise.resolve(
dispatch({
type: "add",
data: linkedData
}));
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Samra |
