简体   繁体   中英

Error while passing params in axios with React

I'm trying a GET request with Axios by passing certain params as follows,

const fetchData = async () => {
    const response = await axios
      .get(config.App_URL.getAllMock, {
        params: {
          customHostName: customerData,
          type: "mock",
        },
      })
      .catch((error) => {
        console.error(`Error in fetching the data ${error}`);
      });
    let list = [response.data.routeManager];
    setData(list);
    setLoading(true);
  };

customerData is fetched from another object passed via contextAPI to this component.

 const [options, setOptions] = useContext(CustomerContext);

And then it is mapped as follows,

const hostNames = [];
  options.map((name, index) => {
    hostNames.push(name.customer.customHostName);
  });
  const customerData = hostNames[0];

The request is failed with 404 since the customerData is not getting passed as a parameter into the payload. So when i checked the log url is like this,

htts://abc.com/v1/route/getAllRoutes?type=mock 404

I tried to log the value of customerData then in that case I can see the expected value to be passed. Any idea on how to pass the customHostName as param into the payload?

Updated the questions with component I'm referring to,


const MainContent = () => {
  const [options, setOptions] = useContext(CustomerContext);

  const hostNames = [];
  options.map((name, index) => {
    hostNames.push(name.customer.customHostName);
  });
  const customerData = hostNames[0];

  // Get all the mock
  const fetchData = async () => {
    const response = await axios
      .get(config.App_URL.getAllMock, {
        params: {
          customHostName: customerData,
          type: "mock",
        },
      })
      .catch((error) => {
        console.error(`Error in fetching the data ${error}`);
      });
    ....
    ....
    ....
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div>
     ....
     ....
     ....
    </div>
  );
};

export default MainContent;


You are using a options variable get from the context and If this variable is get from the async function, you need to listen changes on this variable by adding this variable into the useEffect dependency array.

Your version did not work because you were calling fetchData function only one time (after the initial render).

  const fetchData = (customerData) => {
    ...
  }  

   useEffect(() => {
      if(options) {
       const hostNames = [];
       options.map((name, index) => {
       hostNames.push(name.customer.customHostName);
       });
        const customerData = hostNames[0];

        fetchData(customerData);
      } 
     }, [options]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM