Search code examples
javascriptreactjsreduxpromisereactstrap

Why the state is still showing Promise while using redux? and how should I access the array inside the result?


The state here is showing a promise when I console log the result. How can I access the array inside the promise result I tried Object.key and map but it nothing worked

> import React, { useEffect, useState } from 'react'; import {
> useDispatch, useSelector } from 'react-redux'; import { fetchStocks }
> from '../Redux/stocks/stockreducer';
> 
> 
> 
> export const Home = () => {
> 
> const dispatch = useDispatch(); useEffect(() =>
> dispatch(fetchStocks),[dispatch]); let result = useSelector((state) =>
> state.stocks); console.log(result)   return (
> 
>     <div>
>      <h1>test</h1>
>     </div>   ); }

and this is where I fetch data from API using axios and I thought that by using then I can access the array inside the Promise Object but I cant

> import Axios from 'axios';
> 
> const initialState = [];
> 
> export const LOAD_STOCKS = 'GET_STOCKS';
> 
> export const loadAllStocks = (payload) => ({
>     type: LOAD_STOCKS,
>     payload,   });
> 
> export const fetchStocks = (dispatch) => {
>     var options = {
>       method: 'GET',
>       url: 'https://coinranking1.p.rapidapi.com/coins',
>       params: {
>         referenceCurrencyUuid: 'yhjMzLPhuIDl',
>         timePeriod: '24h',
>         tiers: '1',
>         orderBy: 'marketCap',
>         orderDirection: 'desc',
>         limit: '50',
>         offset: '0',
>       },
>       headers: {
>         'x-rapidapi-host': 'coinranking1.p.rapidapi.com',
>         'x-rapidapi-key': '03518c50f0mshb2f93a5c3fbb56fp1a5e6ajsn175d3c928506',
>       },
>     };
>     let result = Axios.request(options).then((response) => response.data).then((result) => result.data.coins);
>     dispatch(loadAllStocks(result))
>     return result
>          };
>  
> 
> 
> const Stocksreducer = (state = initialState, action) => {
>     switch (action.type) {
>       case LOAD_STOCKS:
>         return action.payload
>       default:
>         return state;
>     }   };
> 
>   export default Stocksreducer;

Solution

  • You've declared fetchStocks as a synchronous function, so you are dispatching the return Promise object from the axios request and not the resolved value.

    Either dispatch the result value from within the Promise chain:

    export const fetchStocks = (dispatch) => {
      const options = {
        ...
      };
      Axios.request(options)
        .then((response) => response.data)
        .then((result) => {
          dispatch(loadAllStocks(result.data.coins));
        })
        .catch(error => {
          // handle any rejected Promises or errors
        });
    };
    

    Or convert fetchStocks to an async function and await the Promise to resolve.

    export const fetchStocks = async (dispatch) => {
      const options = {
        ...
      };
    
      try {
        const response = await Axios.request(options);
        const result = response.data;
        dispatch(loadAllStocks(result.data.coins));
      } catch(error) {
        // handle any rejected Promises or errors
      }
    };