1

I'm getting data from axios by using axios.get and saving the data in a state, and then trying to use that data in a component's prop named disabledDates so i insert the state in the prop and nothing happens but when i put the same data in a const it works

const [selected, setSelected] = useState("");

const url = "http://000.000.0.00:0000/calendar";

const [data, setData] = useState("");

useEffect(() => {
    // Update the document title using the browser API
    axios
        .get(url)
        .then((res) => setData(JSON.stringify(res.data[0].date)))
        .catch((err) => {
            console.error(err);
        });
}, [data]);

console.log(data);

return (
    <SafeAreaView style={styles.container}>
        <CalendarPicker
            onDateChange={(date) => setSelected(date)}
            disabledDates={data}
            disabledDatesTextStyle={{ color: "red" }}
        />
    </SafeAreaView>
);

this is the code that contains the issue

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Nathan E
  • 63
  • 6
  • What do you mean it doesnt work? Does it say that dataa is null? – jsonderulo Feb 09 '22 at 22:29
  • `axios.get` is asynchronous – Bravo Feb 09 '22 at 22:34
  • When i use const data = ["2022-02-11T09:00:00.000Z"] for example (which is the same data as the axios data that im getting from nodejs) in disabledDates the date that i insert in actually get disabled but when i use the axios data which is the state dataa it does not work. – Nathan E Feb 09 '22 at 22:34
  • Inside the .then callback. Did you put the console.log there and see if JSON.stringify(res.data[0].date)) has someting? – Said Torres Feb 09 '22 at 22:44
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Joe Feb 09 '22 at 22:55
  • @SaidTorres yes i console logged the data and it logged it without any issue the problem is with asynchronous as they said in the comments – Nathan E Feb 09 '22 at 23:14

1 Answers1

1

I see two things wrong with your react code.

  1. your use of useEffect is incorrect.

You have dataa as a dependency. Every time your axios request finishes and it sets the data on the state, dataa will change and you will remake the request going into an infinite loop.

  1. You use JSON.stringify() to convert a Json response to a string.

I am not aware which specific library you are using for the date picker but it is unlikely that it expects a string.

Axios responses are already a JavaScript object so just set that to the state of your component, no need to stringify. This will depend on the documentation of the library you are using and in which format they expect the data.

Wowkster
  • 197
  • 3
  • 9
PanBama
  • 11
  • 1