Home > Software engineering >  Is it possible to use "If" in Axios(React.js)?
Is it possible to use "If" in Axios(React.js)?

Time:01-06

I want to change URL in Axios by using if. However looks something wrong.

Is it possible to use "If" in Axios(React.js)?

I can see how console.log(building_state); is in console.

The error is

SyntaxError: /Users/xxx/Desktop/webapp/src/components/Setting.js: Unexpected token

Setting.js

  const building_state = useSelector(state => state.building_state.building_state);

  console.log(building_state);
  
  
  const getRoomName = async(data) => {
    
    await axios.get(
      if (building_state == "condo") {'xxx.com',},
      elif (building_state == "office") {'xxx2.com',},
      else (building_state == "house") {'xxx3.com',},
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${cookies.get('accesstoken')}`
        },
      })
      .then(result => {
        console.log(result.data)
        setRoomName(result.data.home_rooms);  
      })
      .catch(err => {
        console.log(err);
      });
  }

CodePudding user response:

...

const url = {
 "condo": "xxx.com",
 "office": "xxx2.com",
 "house": "xxx3.com"
}[building_state]

await axios.get(
 url,
 {
    headers: {

...

You can't use If operator inside an axios call. But you can declare a variable before your axios call and change it however you want. The above const url is just an another way of writing conditional in a neat way.

CodePudding user response:

Yes, but your syntax is wrong.

The 1:1 equivalent of what you are doing:

const url = building_state == "condo"
    ? 'xxx.com'
    : building_state == "office"
        ? 'xxx2.com'
        : 'xxx3.com'

Alternatively, use switch-case syntax

CodePudding user response:

You can use a Switch like this.

This code shuld do the trick you want.

    const getRoomName = async(data) => {

    let api_request = '';



   switch (building_state) {

  case "condo":
    api_request = "xxx.com";
    break;
  case "office":
     api_request = "xxx1.com";
    break;
  case "house":
     api_request = "xxx2.com";
    break;
  default:
    console.log("Something went wrong...");
    return;
}
    
    await axios.get(api_request),
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${cookies.get('accesstoken')}`
        },
      })
      .then(result => {
        console.log(result.data)
        setRoomName(result.data.home_rooms);  
      })
      .catch(err => {
        console.log(err);
      });
  }
  • Related