I built a php backend for my ReactJS frontend.
My mysql users
table has a checkedIn
column that is stored as tinyint
. I am fetching it like:
<?php // ... $getUser = "SELECT * FROM `users` WHERE `uid`=:uid AND `unique_id`=:unique_id"; $getUser_stmt = $conn->prepare($getUser); $getUser_stmt->bindValue(':uid', $uid,PDO::PARAM_STR); $getUser_stmt->bindValue(':unique_id', $unique_id,PDO::PARAM_STR); $getUser_stmt->execute(); //...
And in my frontend:
useEffect(() => { axios .get(`${config.server}/api/user.php?uid=${match.params.uid}`) .then((result) => { console.log(result.data.message); setUser(result.data.message); }) .catch((error) => console.error(error)); }, [match.params.uid]);
My log gives me:
{ "id": "5", "uid": "A0005", "unique_id": "1384773b4df62", "mail": "mail@test.com", "date_checkin": "2021-05-03 11:00:35", "checkedIn": "1" }
How can I modify my backend or my frontend, to have a real boolean value for checkedIn
in the frontend?
I expect:
{ "id": 5, "uid": "A0005", "unique_id": "1384773b4df62", "mail": "mail@test.com", "date_checkin": Date Mon May 03 2021 17:15:27 GMT+0200, "checkedIn": true }
As a side effect: How can I cast the id to Number and the timestamp to Date?
Advertisement
Answer
Create a function convert
do these conversion:
let user = `{ "id": "5", "uid": "A0005", "unique_id": "1384773b4df62", "mail": "mail@test.com", "date_checkin": "2021-05-03 11:00:35", "checkedIn": "1"}`; function convert(data){ data["id"] = data["id"]*1;//Int data["checkedIn"] = !(data["checkedIn"]==='0');//Bool data["date_checkin"] = Date(data["date_checkin"]);//Date return data; } convert(JSON.parse(user));
Note: user has JSON format. So convert it to real object using function JSON.parse()