Home > Software engineering >  Handling PHP response with Axios/React Native
Handling PHP response with Axios/React Native

Time:12-04

I'm a React Native beginner, please excuse basic questions. I'm having trouble handling json returned from PHP in react native using axios get.

My php returns (have tried both with and without headers part, and also tried with/without json_encode):

<?php

 $json ="[{
        id: 1,
        title: 'List Item One',
        description: 'test1'
    },
    {
        id: 2,
        title: 'List Item Two',
        description: 'test2'
    }]";


header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);

My react native function is below (with the part I'm trying to get to work commented out)


    const [messages, setMessages] = useState([]);

    useEffect(() => {
        loadMessages();
    }, []);

    const loadMessages = async () => {

        let res = await axios.get('https://example.com/test_messages.php');
        //setMessages(res.data);
        console.log(res.data);
    }

    return (
        <Screen style={styles.screen}>

        <FlatList 
        
        data={messages}
        keyExtractor={message => message.id.toString()}
        renderItem={({item}) => (

The console.log seems to work and returns:

[{
        id: 1,
        title: 'List Item One',
        description: 'test1'
    },
    {
        id: 2,
        title: 'List Item Two',
        description: 'test2'
    }]

but when I try to use the commented part instead, I get this error:

"undefined is not an object ('evaluating message.id.toString')"

It seems to just be formatting the output because the console.log seems fine. Further, when I hard code the array into a variable and use it in the useState function, it works fine also.

CodePudding user response:

The format of this json maybe incorrect, you can check it at enter image description here

  • Related