Search code examples
javascriptreactjsreduxreact-hookslifecycle

React renders my Component before it actually has Data


So I'm hard stuck on this Problem... normally I would just do a "ComponentDidMount" but since I'm trying to avoid using classes and only use react hooks I got stuck with the Problem.

My Component renders before it gets any Data from the API, so my .map function won't work as it has not recieve any data.

Shop.js

import React, { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { listShops } from "../../Redux/actions/shopActions";

const Shop = () => {
  const userShop = useSelector(state => state.shop);
  const auth = useSelector(state => state.auth);
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(listShops(auth));
  }, []);

console.log("Look at my userShop",userShop.shop)
  return (
      <div>
       {userShop.map(shop=>(<div>{shop}</div>))}
              {console.log("How often do I Render?")}
    </div>
  );
};

export default Shop;

ShopAction.js

import {GET_SHOPS} from "./types";

export const listShops = userData => async dispatch =>{
    const userId = userData.user.id;
    await axios.get(`/api/shops/shops/user/${userId}`)
    .then(
        res => {
        const user = res.data;
        dispatch({
            type: GET_SHOPS,
            payload: user.shops
        })})
}

shopReducer.js


const initialState = {}

export default function(state = initialState, action) {
    switch (action.type) {
      case GET_SHOPS:
        return {
            ...state,
            shop:action.payload
        }
      default:
        return state;
    }
  }

Solution

  • if(!userShop){
       return <h1>loading<h1>;
     }
     return (
         <div>
          {userShop.map(shop=>(<div>{shop}</div>))}
       </div>
     );