A video with the behavior, I am clicking one time in 'A' and one time 'D', alternatively and is like there is two states, really strange! https://www.loom.com/share/ba7a97f008b14529b15dca5396174c8c
And here is the action to update the description!
if (action.type === 'description') {
const { payload } = action;
const { description } = payload;
const objIndex = state.findIndex(obj => obj === payload.state);
state[objIndex].description = description;
return [...state];
}
And this is the big picture as requested, I tried to simplify to the code that I am testing in description input:
//outside component
const reducer = (state, action) => {
if (action.type === 'initialState') {
const { payload } = action;
console.log('state', state);
console.log('payload', payload);
return state.concat(payload);
}
if (action.type === 'description') {
const { payload } = action;
const { description } = payload;
const objIndex = state.findIndex(obj => obj === payload.state);
state[objIndex].description = description;
return [...state];
}
};
//inside component
const [states, dispatch] = useReducer(reducer, []);
function updateInitialState(value) {
dispatch({ type: 'initialState', payload: value });
}
function updateDescription(payload) {
dispatch({ type: 'description', payload });
}
useEffect(() => {
states.forEach(state => {
const descriptionInput = (state.status === undefined || state.status === 'available') && (
<FormInput
name="description"
label="Descrição"
input={
<InputText
value={state.description || ''}
onChange={({ target: { value } }) => {
const payload = { description: value, state };
updateDescription(payload);
}}
placeholder="Descrição"
/>
}
/>
);
const index = states.findIndex(e => e === state);
const updateArray = arrayInputs;
updateArray[index] = [descriptionInput];
setArrayInputs(updateArray);
});
}, [states]);