0

This questin will be more clear if i show the code:


initializing state with an empty array is easy:
export default function MyComponent() {
  const [state, setState] = useState([]);
}

however, i have an array of paths and i need to create an object for each path like this:

{
  source: path,
  options: { type: 'local' }
}

how am i supposed to initialize state with an array of objects which is created using a loop?
i tried this approach but didnt work:

export default function MyComponent({ paths }) {
  const [state, setState] = useState([ paths.map((path) => ({source: path, options: {type: 'local'} }) ]);
}
1
  • 1
    Don't put [ and ] outside of paths.map, try this. Commented Nov 21, 2021 at 18:27

1 Answer 1

1

You can try to use spread operator:

export default function MyComponent({ paths }) {
    const [state, setState] = useState([...paths.map((path) => ({source: path, options: { type: 'local' }, }))]);
}
Sign up to request clarification or add additional context in comments.

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.