Search code examples
reactjsreduxredux-saga

how to use results from Api-request without putting them to the state React Redux Saga


I want to use results that I got from Api-request use directly in the render(). Can I do it?

const fetchUsersFromApi = () => fetch('https://jsonplaceholder.typicode.com/users?_limit=10')

function* fetchUserWorker() {
    const data = yield call(fetchUsersFromApi)
    const json = yield call(() => new Promise(res => res(data.json())))
    yield put(setUsers(json))
}

Solution

  • No you can't do it . Considering you are firing the API call after the component is mounted inside your useEffect for function component or componentDidMount in case of class component .

    You need a state to hold the initial users value . Initially users will be an [] and once you make the API call your users might be list of users [{}, {}]. Now if you see here we are changing the value from [] to [{}, {}] over a period of time. State provided by react is for this purpose . Whenever a value changes over a period of time either by API calls or by user Interactions then it has to be held in State .