skip to Main Content

I’m working on a react project where I’m trying to fetch a GET api using useEffect react hook. But the useEffect doesn’t seem to work and it gets skipped and rest everything works. I tried the same code on codesandbox and it works without any issues and useEffect works but not in my local environment. I’ve looked at versions in my package.json and also created a new project from scratch but the issue still exists. I don’t know if I have to paste any code or my package to understand more. Any help is appreciated.

I’ve tried using the same code in codesandbox it worked but not locally. Adding the code, this code works on codesandbox but not locally. I feel if it has something to do with other parts of my project.

adding more details: here is the working codesandbox link https://codesandbox.io/s/zen-wu-hllizk?file=/src/App.js

my issue here is everything works as expected on codesandbox but in my local environment useEffect is not triggered.

import { useEffect, useState } from "react";
import axios from "axios";
import Grid from "@mui/material/Grid";
import Box from "@mui/material/Box";
import { makeStyles } from "@mui/styles";
import { styled } from "@mui/material/styles";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import AdjustIcon from "@mui/icons-material/Adjust";
import Rating from "@mui/material/Rating";
import FavoriteIcon from "@mui/icons-material/Favorite";
import FavoriteBorderIcon from "@mui/icons-material/FavoriteBorder";
import "./MenuList.css";

const StyledRating = styled(Rating)({
  "& .MuiRating-iconFilled": {
    color: "#ff6d75"
  },
  "& .MuiRating-iconHover": {
    color: "#ff3d47"
  }
});

const theme = createTheme({
  components: {
    // Name of the component ⚛️
    Box: {
      defaultProps: {
        padding: 0
      }
    }
  }
});
const useStyles = makeStyles((theme) => ({
  buttonHolder: {
    position: "absolute",
    bottom: "1px",
    right: "3px",
    letterSpacing: "1px",
    padding: "5px"
  },
  addButtons: {
    backgroundColor: "#2a265f",
    border: "0",
    borderRadius: "50px",
    boxShadow: "0 10px 10px rgb(0 0 0 / 20%)",
    color: "#fff",
    fontSize: "18px",
    padding: "4px 8px",
    cursor: "pointer"
  },
  categoryHolder: {
    display: "inline-flex",
    verticalAlign: "middle"
  }
}));

const baseURL = "";

const App = () => {
  const [menu, setMenu] = useState("");

  console.log("before useEffect:", menu);

  useEffect(() => {
    axios.get(baseURL + "/menuGet").then((response) => {
      setMenu(response.data);
    });
    console.log("res:");
  }, []);

  console.log("after useEffect", menu);

  const classes = useStyles();
  console.log("menu", menu);

  return (
    <ThemeProvider theme={theme}>
      <Grid className="courses-container" item xs={12}>
        <Grid>
          {menu !== ""
            ? menu.map((item) => {
                return (
                  <Grid className="course">
                    <Box className="course-preview">
                      <Box
                        component="img"
                        className="dish-image"
                        src={
                          "https://foodappdata.s3.ap-south-1.amazonaws.com/josh/" +
                          item.image
                        }
                        alt={"the menu picture for" + item.itemName}
                      />
                    </Box>
                    <Grid className="course-info">
                      {/* <div className="progress-container">
                                    <div className="progress"></div>
                                    <span className="progress-text">
                                        6/9 Challengess
                                    </span>
                                </div> */}
                      <Box className={classes.categoryHolder} component="span">
                        {" "}
                        <AdjustIcon
                          sx={{
                            color: "green",
                            display: "inline",
                            fontSize: "small"
                          }}
                        />
                        <h6> &nbsp;Dish Category</h6>{" "}
                      </Box>
                      <h5>{item.itemName}</h5>
                      <h5>₹ {item.price}</h5>
                      <StyledRating
                        name="customized-color"
                        defaultValue={2}
                        getLabelText={(value) =>
                          `${value} Heart${value !== 1 ? "s" : ""}`
                        }
                        precision={0.5}
                        icon={<FavoriteIcon fontSize="inherit" />}
                        emptyIcon={<FavoriteBorderIcon fontSize="inherit" />}
                        size="small"
                      />
                      {/* <button className="btn">Add</button> */}
                      <Box className={classes.buttonHolder} component="span">
                        <Box component="button" className={classes.addButtons}>
                          -
                        </Box>{" "}
                        1{" "}
                        <Box component="button" className={classes.addButtons}>
                          +
                        </Box>
                      </Box>
                    </Grid>
                  </Grid>
                );
              })
            : null}
          <Grid className="course">
            <Box className="course-preview">
              <Box component="img" className="dish-image" src="./logo512.png" />
            </Box>
            <Grid className="course-info">
              {/* <div className="progress-container">
                        <div className="progress"></div>
                        <span className="progress-text">
                            6/9 Challengess
                        </span>
                    </div> */}
              <Box className={classes.categoryHolder} component="span">
                {" "}
                <AdjustIcon sx={{ color: "green", display: "inline" }} />
                <h6> &nbsp;Dish Category</h6>{" "}
              </Box>
              <h5>Chicken Tangdi Kebab</h5>
              <h5>₹ 369</h5>
              <StyledRating
                name="customized-color"
                defaultValue={2}
                getLabelText={(value) =>
                  `${value} Heart${value !== 1 ? "s" : ""}`
                }
                precision={0.5}
                icon={<FavoriteIcon fontSize="inherit" />}
                emptyIcon={<FavoriteBorderIcon fontSize="inherit" />}
                size="small"
              />
              <button className="btn">Add</button>
              {/* <Box className={classes.buttonHolder} component="span">
                    <Box component="button" className={classes.addButtons}>-</Box> 1 <Box component="button" className={classes.addButtons}>+</Box>
                    </Box> */}
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    </ThemeProvider>
  );
};

export default App;

2

Answers


  1. I think you should define a async function and call it in the useEffect.
    try this:

    useEffect(() => {
        const getData = () => {
          const {data} = await axios.get(baseURL + "/menuGet");
          return data;
        });
        const menuData = await getData();
        setMenu(menuData)
        console.log("res:");
      }, []);
    
    Login or Signup to reply.
  2. here’s the sollution

    useEffect(() => {
      async () => {
        const response = await axios.get(`${baseURL}/menuGet`)
        setMenu(() => response.data);
        console.log(response)
      }()
    }, []);
    

    what this is doing:
    first we creates an async arrow function inside useEffect with and then we call it wit with ():

    // assing the function
    async () => {
    ....
    // call it with ()
    }()
    

    as it is an async function you should await for the promise to resolve, in this case, await for axios to fetch your data 😀

    PS.: it’s more beauty to concat your strings using backticks:

    const myVar = 'some'
    const otherVar = true
    console.log(`${myVar}${otherVar? 'thing' : 'where' }`)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search