I am trying to make a select tag dynamically in react

Viewed 63
let select_options = []
export const serverCall = async (value) => {
  try {
    const response = await axois.post('test/', value)
      .catch(error => {
          some error code ..

        }
      })
      if (response && response.data) {
      select_options = response.data
    }
  } catch (error) {
    
  } finally {
    
  }
}

export async function makeSelectTag(type_code,group_code) {
  await serverCall({'type_code':type_code,'group_code':group_code})
  console.log(select_options) //It clearly contains the value I want.
  return (<Select style={{ width: 150 }}  >
  {options.map((item) => (
    <Option key={item.code_id}>{item.code_name}</Option>
     ))}                
  </Select>

);
}
export default(commonCodeCall, makeSelectTag)

The code above is called from the code below.

import makeSelectTag from '../myPath'
....
return (
      <div>
        <Form.Item>
          {makeSelectTag('type_code','group_code')}
        </Form.Item>
       ...

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

How can I solve the problem and make it work?

2 Answers

you shouldn't really make a makeSelectTag function. Instead create a SelectTag component that takes data and load it into some state on mount stage:

export function SelectTag({ type_code, group_code }) {
  const [options, setOptions] = useState([])

  useEffect(() => {
    const getOptions = async () => {
      const selectedOptions = await serverCall({ type_code, group_code })
      setOptions(selectedOptions)
    }

    getOptions()
  }, [])

  return (
    <Select style={{ width: 150 }}>
      {options.map((item) => (
        <Option key={item.code_id}>{item.code_name}</Option>
      ))}
    </Select>
  )
}

and at your component call it as:

    <Form.Item>
      <SelectTag type_code='foo' group_code='bar' />
    </Form.Item>
{options.map((item) => (
    <Option key={item.code_id}>{item.code_name}</Option>
     ))}                
  </Select>
)}
  • please rewrite options into select_options.
  • I hope it will work successfully. Nice day:)
Related