score:0

Accepted answer

Your current initial state is an empty array, and you are trying to access pollOptions, which is a property that doesn't exist on an empty array.

If you don't need anything, but pollOptions, leave the initial state as an empty array, use polls and not polls.pollOptions when mapping the data, and make sure to set pollOptions as the state:

export const EditPolls2 = () => {
  const { _id } = useParams();
  const [polls, setPolls] = useState([]);

  useEffect(() => {
    axios.get(`/polls/${_id}`).then((p) => {
      setPolls(p.data.pollOptions); // set the pollOptions array as the state
    });
  }, [_id]);

  return (
    <div>
      <p>edit polls 2</p>
      <div>
        <ul>
          {polls.map((p) => ( // use polls and not pollOptions
            <li key={p.pollId}>{p.option}</li>
          ))}
        </ul>
      </div>
    </div>
  );
};

If you do need the entire object (data) in the state, don't use initial state, and use optional chaining (?.) when mapping the array. If the state is undefined, the mapping would be skipped:

export const EditPolls2 = () => {
  const { _id } = useParams();
  const [polls, setPolls] = useState(); // no initial state

  useEffect(() => {
    axios.get(`/polls/${_id}`).then((p) => {
      setPolls(p.data);
    });
  }, [_id]);

  return (
    <div>
      <p>edit polls 2</p>
      <div>
        <ul>
          {polls.pollOptions?.map((p) => ( // optional chaining
            <li key={p.pollId}>{p.option}</li>
          ))}
        </ul>
      </div>
    </div>
  );
};

Related Query

More Query from same tag