2

Working on a little project of mine and ran into an issue. I am using the "ASOS" API and I need to dynamically add key and value to the parameters that it needs to find the correct product. It is to pick for example color, size, price range etc. Issue is, all things I've tried haven't ended up in a success.

How do I dynamically add key and value to an object?

Something like this:

currency: "USD",
sizeSchema: "US",
lang: "en-US",
newKey: newValue

Here is my code:

const FetchAPI = (props) => {
  const [product, setProducts] = useState([]);
  // Key and Value
  let facetKey = props.facetKey;
  let facetValue = props.facetValue;

// Sets the paramaters
  let params = {
    store: "US",
    offset: props.offset,
    categoryId: props.categoryId,
    limit: props.limit,
    country: "US",
    sort: "freshness",
    currency: "USD",
    sizeSchema: "US",
    lang: "en-US",
  };
  // Need to add my "facetKey" and "facetValue" to "params".

  useEffect(() => {
    const options = {
      method: "GET",
      url: "https://asos2.p.rapidapi.com/products/v2/list",
      params: params,
      headers: {
        "x-rapidapi-key": "",
        "x-rapidapi-host": "",
      },
    };

    axios
      .request(options)
      .then(function (response) {
        setProducts(response.data.products);
        props.items(response.data.itemCount);
        props.facets(response.data.facets);
        console.log(response.data.facets);
      })
      .catch(function (error) {
        console.error(error);
      });
  }, [props.offset, props.limit]);

  return (
    <div>
      <div className={classes.container}>
        {product.map((product) => (
          <ProductCard
            key={product.id}
            img={product.imageUrl}
            name={product.name}
            price={product.price.current.text}
          />
        ))}
      </div>
    </div>
  );
};

Thanks!

Keep in mind The facetKey and facetValue return string values, and if the user havent picked a "facet", or an option to filter the products. Then it returns undefined, can of course change this to null.

2 Answers 2

3

You can use the [] operator with objects.

In general:

let obj = {};
let key = 'x';
let value = 3;

obj[key] = value;
console.log(obj);
console.log(obj[key]);

In your example:

let facetKey = props.facetKey;
let facetValue = props.facetValue;

// Sets the paramaters
let params = {
  // ...
};
// Need to add my "facetKey" and "facetValue" to "params".

if (facetKey)
  params[facetKey] = facetValue;
Sign up to request clarification or add additional context in comments.

3 Comments

Ahh okay, I see. Yea that works! Now it just has to refresh the products, would adding params to the [] in useEffect work or would it be simpler with a page reload?
I think you're asking how to update params before it's used in useEffect()? If so, your snippet doesn't show facetKey and facetValue being changed, but assuming it's changed in your full code, then yes you can just move the params[k] = v to inside useEffect().
Ah yes, I see. That works flawlessly! Just need it to be able to filter multiple facey keys and values. I know that I need to use ... so far, but where it shall be I don't know! haha, thanks for the help!
1

You can write the code as follows.

let params = {
    store: "US",
    offset: props.offset,
    categoryId: props.categoryId,
    limit: props.limit,
    country: "US",
    sort: "freshness",
    currency: "USD",
    sizeSchema: "US",
    lang: "en-US",
    [facetKey]: facetValue
};

And if facetKey can be undefined, you can do like this.

let params = {
    store: "US",
    offset: props.offset,
    categoryId: props.categoryId,
    limit: props.limit,
    country: "US",
    sort: "freshness",
    currency: "USD",
    sizeSchema: "US",
    lang: "en-US",
};

facetKey && params = { ...params, [facetKey]: facetValue }
// or
if (facetKey) {
    params = { ...params, [facetKey]: facetValue }
}

Comments

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.