Search code examples
javascriptarraysreactjsuse-effectuse-state

create a new array, removing duplicates and setting state with React


I have a MenuOptions component that I pass an options prop to. Options is a large array of objects. Each object has a nested array called 'services' inside services is an object with a key 'serviceType' which is the only value I want. I want to take all those values, push them into a new array and remove any duplicates if there are any, and then map through that new array and display each item in an 'option' html tag.

here is my createArray function:

    const createNewArray = () => {
        let optionsArr = []
        let uniqueArr;

        options.map((option) => {
            option.services.map((service) => optionsArr.push(service.serviceType))
        })
        uniqueArr = [...new Set(optionsArr)];
        return uniqueArr;
    }

uniqArr seems to be holding what I want but now I want to set this to a piece of global state. Trying something like this does not work. array seems to still be set as null

    const [array, setArray] = useState(null)

   useEffect(() => {
      setArray(createNewArray())
   }, [])

any solutions? Thanks


Solution

  • 1) You should add your array state initial value as an empty array:

    const [array, setArray] = useState([]);
    

    Live Demo

    Codesandbox Demo

    2) You can simplify the creating of a new array as:

    const createNewArray = () => [
      ...new Set(options.flatMap((o) => o.services.map((obj) => obj.serviceType)))
    ];
    

    3) set array state in useEffect as:

    useEffect(() => {
      setArray(createNewArray());
    }, []);