A
A
azemlyankin2021-06-30 20:56:13
React
azemlyankin, 2021-06-30 20:56:13

What is the correct way to get data from the server into a React Redux project?

There is a project, some online store. With the help of the following asset, I get an array in the store:

export function cardsFetchData(url){

  return(dispatch) => {
    fetch(url)
      .then(response => {
        if(!response.ok){
          throw new Error(response.statusText)
        }
        return response
      })
      .then(response => response.json())
      .then(cards => dispatch(addState(cards)))
  }
}

How to make it so that first the data from the server is loaded into the store, only then the components are rendered?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Valery, 2021-06-30
@azemlyankin

Let's say you have a root component that renders all the others, usually <App />.
In such a case, you can call(dispatch) cardsFetchDataduring the mouting phase of the root component.
In your case, you should have some kind of data loading flag - like isLoading. Therefore, you can conditionally render all your child components by condition:

const App = () => {
    // отправка экшена на запрос данных + селектор получения статуса загрузки
    if (isLoading) {
        return null;
    }
    
    return (...) // тут у вас по идее уже данные находятся в сторе и вы можете писать логику отображения
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question