Hemanth
Hemanth

Reputation: 151

How do i dynamically append url when onclick event occured?

this is where i making a api call

export const filteredProducts = (e) => {
  const radio = e.target.checked;
  return dispatch => {
    dispatch({type: actionTypes.TOGGLE_LOAD});
    axios.get(radio ? `/store?limit=9&skip=0&subcategory=${e.target.value}` : 
    `/store?limit=9&skip=0`)
    .then(response => {
      dispatch(setFilter(response.data, radio));
    })
  }
}

i wanted to do something like this. whenever i click on filter button the event has to appended to the existing url.

enter image description here.

axios.get(`/store?limit=9&skip=0&subcategory=${e.target.value}&brand=${e.target.value}&{e.target.value}`)

I really do not know how to frame this question. If you want me to make it more clear I'll try to do that. since this is the client project i could not share the code base. Thanks in advance

Upvotes: 1

Views: 341

Answers (1)

mplungjan
mplungjan

Reputation: 178011

Use the URL and url.searchParams API

const url = new URL("/store?limit=9&skip=0");

const makeUrl = (name, value) => {
  if (name) {
    url.searchParams.append(name,value); // or searchParams.set to not append
  }
  return url;
};


export const filteredProducts = (e) => {
  const radio = e.target.checked;
  return dispatch => {
    dispatch({type: actionTypes.TOGGLE_LOAD});
    axios.get(radio ? makeUrl(e.target.name, e.target.value) : makeUrl())
      .then(response => {
        dispatch(setFilter(response.data, radio));
      })
  }
}

Upvotes: 2

Related Questions