4

I just wanna know is it possible to use useReducer, as I use it inside UseEffect fetched data => State => useReducer(..., State)

 const [initialData, setInitialData] = useState({ name: 'ass' });
    const [data, dispatch] = useReducer(apiReducer, initialData);

    const Data2 = useFetch('/qaz')

    useEffect(() => {
        setInitialData(Data2)
    }, [Data2])

    useEffect(() => {
        dispatch({ type: 'Different', payload: 'key' })
    }, [initialData])


export function apiReducer(state, action) {
    switch (action.type) {
        case 'Different':
            return { ...state, key: action.payload };
        default:
            return state
    }
}
alimkhan 7007
  • 103
  • 1
  • 5

2 Answers2

6

You cannot change the initial state after the reducer has been created. What you can do is dispatch an action that replaces the entire state. You can use a useEffect hook to dispatch this "REPLACE_STATE" action after the useFetch hook has returned its data.


Reducer

export function apiReducer(state, action) {
  switch (action.type) {
    case "REPLACE_STATE":
      return action.playload;
    case "Different":
      return { ...state, key: action.payload };
    default:
      return state;
  }
}

Component

export default function App() {
  const [state, dispatch] = useReducer(apiReducer, { name: "ass" });

  const fetchedData = useFetch("/qaz");

  useEffect(() => {
    if (fetchedData) {
      dispatch({ type: "REPLACE_STATE", payload: fetchedData });
    }
  }, [fetchedData]);

  const doSomething = () => {
    dispatch({ type: "Different", payload: "key" });
  };
...
Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
0
export default function App() {
  const [state, dispatch] = useReducer(apiReducer, { name: "ass" });
  const [change, setChange] = useState(false)
  const fetchedData = useFetch("/qaz");

  useEffect(() => {
    if (fetchedData) {
      dispatch({ type: "REPLACE_STATE", payload: fetchedData });
      setChange(!change)
    }
  }, [fetchedData]);

  useEffect(() => {
    dispatch({ type: "Different", payload: "key" });
  },[change]);
alimkhan 7007
  • 103
  • 1
  • 5