if( true ) // some condition to check if we need to fetch data
(async () => {
const result = await fetch('http://localhost:3001/employees');
if(result.status === 200) {
const data = await result.json();
**// how to update state with data??**
}
else {
**// how to update state with error??**
}
})();
return newState;
}
default:
return defaultReducer(state, action);
}
Thanks, it is clear to me, you mean that I have to change the status using useState hook that operate externally form middleware reducer.
Is there any way to do this without useState if I don’t use React?
Thanks
The concept is the same for the other bindings, i.e. Angular and Vue. Just instead of useState it’s then a property in the Angular component or a reactive in Vue, handing over the data@Input / prop to JSON Forms.
@sdirix why if I call setFormData in the async call, in the case INIT I receive a waring that I0m changing the status (useState) while another component is rendering? What is the life cycle of the reducer?
Thanks
Init is called as part of the initial rendering, see here.
So if it turns out that the async method is actually not async and can execute immediately, then you will end up calling setState while the component is rendering, triggering an immediate rerendering. That should only be an issue for the “init” action. As init will only be executed once per form life cycle, you could also ignore the warning. Alternatively, if you often end up in a case where there is no real async executed for you, then you could start working with MaybePromise types and fallback and check for actual sync behavior and then behave differently.
Hi @sdirix, I saw in the code:
const [core, setCore] = useState(() =>
middlewareRef.current(
initState.core,
Actions.init(data, schema, uischema, {
ajv,
validationMode,
additionalErrors,
}),
coreReducer
)
);
the core is updated by the middleware in sync, so I can’t call setStatus inside a useState, I mean like this: const [core, setCore] = useState(() => setStatus(…));
But, as far as you know, it is only a warning or it could not works?
Usually async operations take a while and then it doesn’t matter where the async call was triggered from.
The warning appears for you in case you are not using async, or all your async code is already resolved so Javascript might have executed it in sync.
In case you are deliberately not using async, then you should NOT call setState in the reducer. Instead you should just modify the state which you have already in hand in the middleware.