0

I'm trying to pass the formatted (JSON) API results into the redux store. I'm able to retrieve the data and resolve the promise but I can't assign the returned data inside the '.then' method.

Can you please tell me what I'm doing wrong? Also I'm newer so please be kind if I mistake a question. Thank you.

Reducer

import apiTest from "../api/ApiTest";

const initialState = {
  listData: null
};

const contactListReducer = (state = initialState, action) => {
  switch (action.type) {
    case "FETCH":
      console.log("inside switch (reducer) ");
      return getData(state);
    default:
      return state;
  }
};

const getData = (state, action) => {
  console.log("Inside getData");
  let data;
  let request = apiTest().then((results) => {
    data = results;
    console.log("INSIDE THEN");
    console.log(data);
  });
  console.log("OUTISIDE THEN");
  console.log(request);
  return Object.assign({}, state, {
    listData: request
  });
};

export default contactListReducer;

API Code:

import React, { useEffect, useState } from "react";
import axios from "axios";

const apiCall = async () => {
  try {
    const payload = await fetch("https://jsonplaceholder.typicode.com/users");
    const results = await payload.json();
    // console.log(results);
    return results;
  } catch (err) {
    console.log(`error found of type ${err}`);
  }
};

export default apiCall;


NinelSeyer
  • 21
  • 1
  • 4
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – coagmano Sep 10 '21 at 00:03
  • Though for redux in particular, I think you need to use a "thunk" - sounds made up, but helps perform async actions in a reducer – coagmano Sep 10 '21 at 00:04
  • Actually this existing answer [How to dispatch a Redux action with a timeout?](https://stackoverflow.com/questions/35411423/how-to-dispatch-a-redux-action-with-a-timeout/35415559#35415559) is better since it's specific to async work in a redux app. Just consider mentally replace `setTimeout` with your `then` and it works the same – coagmano Sep 10 '21 at 00:09
  • and even better, has suggestions on how to do this more simply than with thunks – coagmano Sep 10 '21 at 00:10
  • Thank you cuagmano. I'm reading more into thunk middleware documentation. – NinelSeyer Sep 11 '21 at 02:04

0 Answers0