React Native hooks usage with multiple objects

Tags: , , ,



I am trying to create a todo list app, with a Share button that can share the todo list you have. The app is almost complete, the other parts of the code is irrelevant I thought but if needed I can post them.

My state is like this:

const [todos, setTodos] = useState([
    {todo: 'Add a todo', key: '1'},
    ]);

My share function is like this – directly taken from the official docs -:

 const onShare = async () => {
    try {
      const result = await Share.share({
        message:
          todos.todo
      });
      if (result.action === Share.sharedAction) {
        if (result.activityType) {
          // shared with activity type of result.activityType
        } else {
          // shared
        }
      } else if (result.action === Share.dismissedAction) {
        // dismissed
      }
    } catch (error) {
      alert(error.message);
    }
  };

Where I render the button and call the function:

<Button color= 'orange' title={'Share'} onPress={onShare}/>

My problem is in the message: part (second code block), I cannot reach my individiual todo inside the todos state. It might be the easiest problem but I couldnt find a way…

Help please 🙂

Answer

Try this way which wrap all data of todo’s in string

const justTodos = todos.map(item => item.todo);
const result = await Share.share({
        message: JSON.stringify(justTodos)
})


Source: stackoverflow