0

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.

Now scenario: I was able to figure out that the issue is on my local system, the same thing works on other local setup and elsewhere but not on my environment. I'm using Mac M1, it used to work before. Maybe it has to do something with new OS update Ventura? any thoughts?

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>&#x20B9; {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>&#x20B9; 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;
5
  • 1
    Post the code that demonstrates the issue Commented Apr 28, 2023 at 16:07
  • Here's some documentation on how to create a React snippet. Commented Apr 28, 2023 at 16:11
  • simply using instance of axios is the issue. Whenever you are loading your app a new instance of axios is required. Create an async await function call it inside use Effect also use loading and setLoading inside that function so that you know if the code has mounted. Commented Apr 28, 2023 at 16:39
  • "I tried the same code on codesandbox and it works without any issues but not locally." you have copy pasted this message 3 times, I guess you had to since stackoverflow limits too much code/text ratio, still, it doesn't help us understand what doesn't work? Commented Apr 28, 2023 at 17:22
  • Do you have a minimal reproducible example? Commented Apr 28, 2023 at 19:28

2 Answers 2

0

Here's the solution:

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

What this is doing: first we create 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 :D

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

const myVar = 'some'
const otherVar = true
console.log(`${myVar}${otherVar? 'thing' : 'where' }`)
Sign up to request clarification or add additional context in comments.

Comments

-2

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

useEffect(() => {
    const getData = async () => {
      const {data} = await axios.get(baseURL + "/menuGet");
      return data;
    });
    const menuData = await getData();
    setMenu(menuData)
    console.log("res:");
  }, []);

2 Comments

await doesn't works inside useEffect body
Oh my bad! const getData = async () => { ... }. now it should work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.