0

I'm writing a reducer that will be used along with React.useReducer hook. Flow is used, but the reducer is suffering from a flow error because Object.assign({}, state ... has {} as an object literal that is incompatible with SearchLocationStateType. The only solution I've found is listing all the properties on each object literal, which is not the right way.

How could I fix this?

type SearchLocationStateType = {
    textAreaFocused: boolean,
    promptsShown: boolean,
};

export const ACTIONS = Object.freeze({
    FOCUS_SEARCH_TEXT: 'FOCUS-SEARCH-TEXT',
    BLUR_SEARCH_TEXT: 'BLUR-SEARCH-TEXT',
});

type ActionType = {
    type: $Values<typeof ACTIONS>,
};

const reducer = (state: SearchLocationStateType, action: ActionType): SearchLocationStateType => {
    switch (action.type) {
        case ACTIONS.FOCUS_SEARCH_TEXT:
            return Object.assign({}, state, {textAreaFocused: true});
        case ACTIONS.BLUR_SEARCH_TEXT:
            return Object.assign({}, state, {textAreaFocused: false});
        default:
            return state;
    }
};
Bertuz
  • 2,390
  • 3
  • 25
  • 50
  • Isn't using type casting sufficient like this: return Object.assign({}, state, {textAreaFocused: true}) as SearchLocationStateType ; – Berk Kurkcuoglu Aug 29 '20 at 14:58
  • maybe you mean `return (Object.assign({}, state, { textAreaFocused: true }): SearchLocationStateType);` but that raises the same problem, just within parenthesis – Bertuz Aug 29 '20 at 15:06
  • Can you post the error message? – Yousaf Aug 29 '20 at 15:07
  • 1
    Just out of curiosity, is there a reason why you prefer Object.assign instead of object destructring? – Berk Kurkcuoglu Aug 29 '20 at 15:08
  • because it's too long since I last touched ES that I didn't figure it out. Destructuring makes it! Can you write it as an answer so as to select it as the solution? Thanks – Bertuz Aug 29 '20 at 15:13
  • 2
    As an alternative, you could always use property spread syntax: `return { ...state, textAreaFocused: true };` – Yousaf Aug 29 '20 at 15:14

0 Answers0