Recently, the project has been iterating constantly, and the work has not stopped. I have encountered large and small problems, but fortunately, they have been gradually solved. It’s been a long time since I wrote down the questions. Pick them up.

There was a requirement in development that multiple interfaces were called in a loop, and the interface calls were called differently depending on the user’s actions, but at the end, all the retrieved data was saved to update the view. For example:

I am a chestnut

 const [result, setResult] = useState({});
    const fetchList = (a)= > {
        serviceList.map(async (item) => {
            const response = await item.service();
            // setState to state after each fetchsetResult({ ... result, [item.key]: response }); }); };Copy the code

This is just a simple example, and real life scenarios are often more complex than this. At first glance this seems fine, but the problem is that once the fetch method above is executed, the result state is not a collection of all the results at all, but the last update…

The first failed attempt

The React setState hook inherits the setState method, so it’s asynchronous. The purpose is to improve performance and avoid unnecessary updates.

A clever brick remover would not be able to get caught up in such a small mound, so one idea would be to define a temporary variable outside the loop to store all the results, and then assign a uniform value to result, hence the following version:

  const [result, setResult] = useState({});
    const fetchList = (a)= > {
        let nowResult;
        serviceList.map(async (item) => {
            const response = await item.service();
            // Get the data and add it to a temporary variable to updatenowResult = { ... nowResult, [item.key]: response };// Remember to update state, because this is an asynchronous call interface, it will not get results outsidesetResult({ ... result, ... nowResult }); }); };Copy the code

The useReducer was successfully resolved

The problem was resolved, but then it was discovered that fetch could be called many times in different situations… Therefore, after the first call, the result is not come and updated to result, and then the second call, and so on, so that it is back to the origin. However, this does not stop my enthusiasm for technology. After constant Googling, I finally found the wonderful use of useReducer. It turns out that useReducer can not only be used for complex status updates, but also can update the status synchronously. Hence the following version:

  const [result, setResult] = useReducer((state, action) = > {
        switch (action) {
        // This is a speculative way of writing. Whatever the action is, update the state as follows
            default:
                return { ...state, ...action };
        }
    }, {});
    const fetchList = (a)= > {
        serviceList.map(async (item) => {
            const response = await item.service();
            // Remember to update state, because this is an asynchronous call interface, it will not get results outsidesetResult({ ... result, [item.key]: response }); }); };Copy the code

In this way, temporary variables are no longer needed and the world is better (~ ~ ▽ ~)

Know more about true love: useReducer

A brief introduction to the useReducer. This is a hook that I don’t use very often. This hook is used for updating complex variables.

const [result, setResult] = useReducer((state, action) = > {
        switch (action) {
            case 'action1':
            return{... state, result1};// Specify the update method
            case 'action2':
            return{... state, result2};// Specify the update method
            default:
                return{... state, ... action }; } }, initialState);Copy the code

This hook declaration has the same form as useState, but the first function that useReducer receives takes the same form as the reducer method defined by Redux. The second parameter is the original state variable.

If you have any questions, please give me a thumbs up if you think it is useful

Part of life is working, and part of work is solving problems to please life, so live well, work well, love well (● world twentyconsciousness)