How can I use an asynchronous javascript function like fetch inside a FormDataConsumer

async/await fetch example
async/await fetch react
fetch api
async/await post request
async arrow function
javascript fetch synchronous
fetch async/await error handling
when to use async/await

I need to use a fetch inside the FormDataConsumer tag but it seems FormDataConsumer does not support async functions. This code didn't work for me:

<FormDataConsumer>
{
    async ({ formData, scopedFormData, getSource, ...rest }) => {
        return await fetch('/api/v1/attributes/'+scopedFormData.single_attributes_label)
        .then(res => res.json())
        .then(data => {
            console.log(JSON.stringify(data));
            //return JSON.stringify(data);
            resolve(JSON.stringify(data));
        });
        return JSON.stringify(scopedFormData);
    }
}
</FormDataConsumer>

I also checked this code and this one also didn't work:

async function getAttrItem(id) {
  return await fetch(`/api/v1/attributes/${id}`).then(response => response.json())
}

...

<FormDataConsumer>
{
    async ({ formData, scopedFormData, getSource, ...rest }) => {
        return await JSON.stringify(getAttrItem(scopedFormData.single_attributes_label));
    }
}
</FormDataConsumer>

But when I use this one, it works in the console:

<FormDataConsumer>
{
    ({ formData, scopedFormData, getSource, ...rest }) => {
        fetch('/api/v1/attributes/'+scopedFormData.single_attributes_label)
        .then(res => res.json())
        .then(data => {
            console.log(JSON.stringify(data));
            //return JSON.stringify(data);
            resolve(JSON.stringify(data));
        });
        return JSON.stringify(scopedFormData);
    }
}
</FormDataConsumer>

Should I use this FormDataConsumer for filling an object and then inside the other FormDataConsumer check the object?

You might wanna do something like this:

const MyComponent = props => {
  const [data, setData] = useState();

  useEffect(() => {
    fetch("/api/v1/attributes/" + props.attribute)
      .then(res => res.json())
      .then(data => {
        setData(data);
      });
  }, [props.attribute]);

  if (!data) {
    return <someloadingindicator />;
  }

  // now you got your data. you can now return some component that uses the data here
};


// now in your component where using the FormDataConsumer
<FormDataConsumer>
  {({ formData, scopedFormData, getSource, ...rest }) => {
    return <MyComponent attribute={scopedFormData.single_attributes_label} />;
  }}
</FormDataConsumer>;

node.js 如何在FormDataConsumer中使用异步Javascript函数(例如 , he FormDataConsumer tag but it seems FormDataConsumer does not support async functions. This code didn't work for me: { async� It can be used inside an Async block only. The keyword Await makes JavaScript wait until the promise returns a result. It has to be noted that it only makes the async function block wait and not

While you can run JavaScript expressions in JSX, it is not a good pattern to bloat it with too much JavaScript logic within JSX. The above logic should be handled within the componentDidMount() lifecycle hook for class components, or in the useEffect hook, for functional components.

In your FormDataConsumer

componentDidMount() {
  fetch('/api/v1/attributes/'+scopedFormData.single_attributes_label)
    .then(res => res.json())
    .then(data => {
        console.log(data);
       // do the rest here
    });
}

or

useEffect(() => {
  fetch('/api/v1/attributes/'+scopedFormData.single_attributes_label)
    .then(res => res.json())
    .then(data => {
       console.log(data);
       // do the rest here
    });
 }, []);

JavaScript Fetch API and using Async/Await - DEV, 这段代码对我不起作用:<FormDataConsumer>{ async ({ formData, How can I use an asynchronous javascript function like fetch inside a� Keep in mind that in order to call a function using the await keyword, it must be within the async function as in the below example. This is just the syntactical sugar of making things more readable, in turn handling the return of a Promise object more seamlessly and feels more like a synchronous function call rather than asynchronously handled.

My issue was fixed with this code:

<FormDataConsumer>
    {
        ({ formData, scopedFormData, getSource, ...rest }) => {
            return scopedFormData && formData && "type" in formData && <ReferenceInput label="Attribute Label" source={getSource('single_attributes_label')} reference={`attributes`} filter={{ document_type: formData.type }}>
            <AutocompleteInput optionText="title" optionValue="id" />
            </ReferenceInput>
        }
    }
</FormDataConsumer>
<FormDataConsumer>
    {
        ({ formData, scopedFormData, getSource, ...rest }) => {
            return "type" in formData && "single_attributes_label" in scopedFormData && <AttribValue source={getSource('single_attributes_value')} reference={`attributes`} filter={{ document_type: formData.type, id: scopedFormData.single_attributes_label, method: "getOptions" }} attribute={scopedFormData.single_attributes_label} {...rest} />
        }
    }
</FormDataConsumer>

const AttribValue = props => {
  const [data, setData] = useState();
  console.log('props', props);
  useEffect(() => {
    fetch("/api/v1/attributes/" + props.attribute)
      .then(res => res.json())
      .then(data => {
        setData({ data });
      });
  }, [props.attribute, props.label]);

  if (!data) {
    return 'Please Wait...';
  }
  let newProp = Object.assign({}, props, { label: "Attributes Value" });
  return data.data.attribute_type == 'multiselect' ? <ReferenceArrayInput {...newProp}><AutocompleteArrayInput optionText="text" optionValue="id" /></ReferenceArrayInput> : <ReferenceInput {...newProp}><AutocompleteInput optionText="text" optionValue="id" /></ReferenceInput>;
};

Using JavaScript's Async/Await Syntax to Fetch Data in a React App , then() function, which supports a callback function for resolving the fetch function. As I said this functions and is fairly readable. In the few short� An async function is a function declared with the async keyword. Async functions are instances of the AsyncFunction constructor, and the await keyword is permitted within them. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

How to return the result of an asynchronous function in JavaScript, Using JavaScript's Async/Await Syntax to Fetch Data in a React App Component but defining it as an async function — this allows my use of� Fetch is a Javascript function that accepts two arguments. The first argument is a stringified URL, and the second is an optional argument that will contain information about your request.

Asynchronous Javascript using Async, How to return the result of an asynchronous function in JavaScript. Find out how to return the result of an asynchronous function, promise based or callback based , using result of that call to be returned from the original function. Like this: performs some asynchronous call in it (for example a fetch() call),� There’s a special syntax to work with promises in a more comfortable fashion, called “async/await”. It’s surprisingly easy to understand and use. Async functions. Let’s start with the async keyword. It can be placed before a function, like this:

React update context value, Well, simply put, async/await allows us to write asynchronous code in a all we need to do is add the async keyword before the function definition, like this: async function asyncFunc() { // fetch data from a url endpoint const� The Async statement is to create async method in JavaScript.The function async is always return a promise.That promise is rejected in the case of uncaught exceptions, otherwise resolved to the return value of the async function. Whats Await in JavaScript. The await is a statement and used to wait for a promise to resolve or reject. It can only

Comments
  • What version of react-admin are you using?
  • react-admin v2.9.9 was used in my project
  • Thanks, I knew about componentDidUpdate but I didn't want to use that. In somehow, using useEffect was my question.
  • @MasoudILDEREMI sorry, I mean componentDidMount, not componentDidUpdate.