cec577
cec577

Reputation: 23

How to display my async request in react admin?

How to display my async request in react admin (function field)? My request is correct. But I have the following error: 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.

I am on new on react-admin and I don't know how to resolve this error. Can you help me? How to display my async request in react admin (function field)? My request is correct. But I have the following error:

export const TreeList = props => (
    <ListGuesser {...props}>
        <FieldGuesser source={"code"} />

        <FunctionField
            label="Image"
            render={
                async (record) => {
                        let content = ''
                let response = await fetch('https://nuxt-api.io.local/api/media_objects')
                   
                    const res = await response.json()
                     content = res['hydra:member'].find(value => { return value['@id'] === record.outlinedImage }).contentUrl || ''


                    return (
                    <img width="100"
                         src={`https://nuxt-api.io.local${content}`} alt="Upload image"
                    />
                );
            }}
        />
    </ListGuesser>
);

Upvotes: 0

Views: 841

Answers (1)

MaxAlex
MaxAlex

Reputation: 3319

Try this option:

const TreeList = (props) => (
  <List {...props}>
      <Datagrid>          
        <MyImageField />
      </Datagrid>
  </List>
)


const MyImageField = (props) => {
  const record = useRecordContext(props)
  const [imageUrl, setImageUrl] = useState('')

  useEffect(() => {
    (async (rec) => {
      let content = ''      
      try {
        const response = await fetch('https://nuxt-api.io.local/api/media_objects')
        const res = await response.json()
        content = res['hydra:member'].find(value => { return value['@id'] === rec.outlinedImage }).contentUrl || ''
      } catch (error) {
        console.warn('MyImageField error:', error)
      }
      setImageUrl(`https://nuxt-api.io.local${content}`)
    })(record)
  }, [record, setImageUrl])

  return <img width="100" src={imageUrl} alt="Upload image" />
}

Upvotes: 1

Related Questions