2

I have a working material ui auto component that has the following code:

     <Autocomplete
              multiple
              options={props.cats}
              defaultValue={editRequest?([props.cats[props.post.category]]):undefined}
              limitTags={2}

This works when props.post.category has just one value in props.post.category.

When there are two values such as 34,36 coming in for props.post.category, it breaks the page with errors. In a normal function, I would use .map to loop through the array. This is inside a defaultValue so I cant figure out how to assign two default values which are basically

props.cats[34] and props.cats[36]

In other words, how can a string separated by commas be converted to individual arrays

input=> 34,35 (stored in props.category)
array=> [props.cats[34], props.cats[35]]

1 Answer 1

1

You could wrap any props.post.category with square bracket, flat it then map, so you don't have to worry about whenever it is a single value or array of values

console.log([34].flat())
console.log([[35, 36]].flat())

const getDefaultValue = () => {
  if (!editRequest) {
    return undefined
  }

  return [props.post.category].flat().map((cat) => props.cats[cat])
}

return (
  <Autocomplete
    multiple
    options={props.cats}
    defaultValue={getDefaultValue()}
    limitTags={2}
  />
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It expects [props.cats[35],props.cats[36]]. I am getting some intermediate value cannot be filtered error. Let me play with this based on your answer.

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.