skip to Main Content

I have an array of objects response that comes from API. I don’t have access to the API to be able to change it.

data = [
   {"label": "Group 1", "value": "1"}, 
   {"label": "Group 2", "value": "2"}, 
   {"label": "Group 3", "value": "3"}
]

I need to display the data, so the label says Post to ${label}.

Can I inject the ‘Post to ‘ string somehow? Do I make a new array from my response?

Here’s how I’m fetching the data:

const [pickerData, setPickerData] = React.useState<{ label: string; value: string }[]>([]);
const fetchPickerData = React.useCallback(async () => {
  const response = await getPostLocations();
  if (!response) return;

  if (response) {
    setPickerData(response);
  }
}, []);

React.useEffect(() => {
  fetchPickerData().catch(console.error);
}, [fetchPickerData]);```

and my data is then loaded into a picker: 

  <Picker
      items={pickerData}
      value={pickerItem}
      onValueChange={(pickerItem) => setPickerItem(pickerItem)}
    />


Things I already tried is trying to inject string into value like value={()=>{`Post to ${pickerItem}`}}, or the same in the setPickerItem in onValueChange but that didn't work

2

Answers


  1. Try it like this

    const [pickerData, setPickerData] = React.useState<{ label: string; value: string }[]>([]);
    const [apiData, setApiData] = React.useState<{ label: string; value: string }[]>([]);
    
    const fetchPickerData = React.useCallback(async () => {
      const response = await getPostLocations();
      if (!response) return;
    
      if (response) {
        setApiData(response);
      }
    }, []);
    
    React.useEffect(() => {
      fetchPickerData().catch(console.error);
    }, [fetchPickerData]);
    
    React.useEffect(() => {
      if (apiData.length > 0) {
        let Temp = [];
        apiData.forEach((item) => {
          let newItem = {
            ...item,
            label: `Post to ${item.label}`
          };
          Temp.push(newItem);
        });
        setPickerData(Temp);
      }
    }, [apiData]);
    
    
    Login or Signup to reply.
  2. You can use Array#map() to create a new array from the response in the format you prefer:

    const fetchPickerData = React.useCallback(async () => {
      const response = await getPostLocations();
      if (!response) return;
    
      if (response) {
        const formattedResponse = response.map(
            ({ label, value }) => ({ 'label': `Post to ${label}`, value })
        )
        setPickerData(formattedResponse);
      }
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search