0

I am trying to sort all objects that match the regex into an array. This does not seem to work with the spread operator and useState, is there any way I can do that? The result I am getting now is the samples thing only gives me the last object that matches it and nothing else. The desired effect I want is all the samples that match get pushed into the samples state.

  const [accessories, setAccessories] = useState([]);
  const [paints, setPaints] = useState([]);
  const [samples, setSamples] = useState([]);

  // Load order into state
  useEffect(() => {
    loadUser();
    getOrderById(match.params.orderId);
  }, []);

  // Load order into state
  useEffect(() => {
    if (!loading) {
      console.log(order.line_items);
      for (let i = 0; i < order.line_items.length; i++) {
        if (order.line_items[i].sku.match(/^(TAC|T.BU.AC)/)) {
          console.log('SKU: ', order.line_items[i].sku);
          //@ts-ignore
          setAccessories([...accessories, order.line_items[i]]);
          console.log(accessories);
        }
        if (order.line_items[i].sku.startsWith('TBA') || order.line_items[i].sku.match(/^TCR(?!0000)/)
          || order.line_items[i].sku.match(/^TCR0000/)) {
          //@ts-ignore
          setPaints([...paints, order.line_items[i]]);
        }
        if (order.line_items[i].sku.match(/^TCR\d+P?\d+SAMP/)) {
          console.log(samples);
          console.log(order.line_items[i]);
          //@ts-ignore
          setSamples([...samples, ...[order.line_items[i]]]);
        }
      }
    }
  }, [loading]);

1
  • order.line_items[i].sku.match(/^TCR(?!0000)/) || order.line_items[i].sku.match(/^TCR0000/) does not make sense - if the sku starts with TCR, at least one of those will evaluate to true. What's the logic you're looking for relating to 0000 there? Commented Mar 26, 2020 at 2:30

2 Answers 2

1

Well there are few mistakes you're doing here.

Mistake 1:

Calling the same setStates way too many times inside a single useEffect block using a for loop, this might greatly affect React's performance. Again, this is clearly a violation of Rules of Hooks, Only Call Hooks at the Top Level

Only Call Hooks at the Top Level

Don’t call Hooks inside loops, conditions, or nested functions.

Mistake 2:

Though this is not as serious as the previous ones, it's still a mistake. Not using better solutions, Use inbuilt JavaScript methods like filter instead of writing your own for loop

useEffect(() => {
  let _accessories;
  let _paints;
  let _samples;

  if (!loading) {
    _accessories = order.line_items.filter(({ sku }) => sku.match(/^(TAC|T.BU.AC)/))

    _paints = order.line_items.filter(({ sku }) => sku.startsWith('TBA') || sku.match(/^TCR(?!0000)|^TCR0000/))

    _samples = order.line_items.filter(({ sku }) => sku.match(/^TCR\d+P?\d+SAMP/))

    // Never use setState inside a for loop
  // of useEffects
  // Also avoid calling same setState multiple times

  // use callback setState if you want to access
  // previous state, but it ain't a compulsory like
  // for class components
  setAccessories(s => [ ...s, ..._accessories ])
  setPaints(s => [ ...s, ..._paints ])  
  setSamples(s => [ ...s, ..._samples ])
  } 

  // return in useEffect has different role
  // than normal functions

}, [loading])


Sign up to request clarification or add additional context in comments.

Comments

0

Spread the results of calling .filter into the calls:

useEffect(() => {
  if (loading) {
    return;
  }
  const items = order.line_items;
  setAccessories([
    ...accessories,
    items.filter(({ sku }) => sku.match(/^(TAC|T.BU.AC)/))
  ]);
  setPaints([
    ...paints,
    items.filter(({ sku }) => sku.startsWith('TBA') || sku.match(/^TCR(?!0000)|^TCR0000/))
  ]);
  setSamples([
    ...samples,
    items.filter(item => item.sku.match(/^TCR\d+P?\d+SAMP/))
  ]);
}, [loading]);

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.