empty text when trying to iterate JSON from axios in react

Advertisements

i have code:

const Forms = () => {
    const [messageText, setMessageText]: any = useState("");
    useEffect(() => {
        const getPosts = () => {
            axios.post('http://localhost:8080/graphql/', {
                query: `
  {
    getPosts(option: true) {
      id
      message
    }
  }  
  `
            })
                .then((res) => {

                    const andrey = res.data.data.getPosts

                    setMessageText(andrey)


                })
                .catch((error) => {
                    console.error(error)
                })
        };
        getPosts()


    }, [])


    console.log(messageText)


    return (
        <div>
            <div style={{alignItems: "center", justifyContent: "center", textAlign: "center"}}>
                {Object.keys(messageText).map((data: any) => (
                    <Form message={data.message}/>
                    ))}


            </div>
            <Input/>
        </div>

    );
};

export default Forms; 

i want to display div elements with json key text, but div elements are empty.If I display just data, then numbers are displayed instead of text on the page. Please, help me.
This is what comes up in my browser:

>Solution :

To begin with, using Object.keys to map messageText is not necessary. It’s already na array, from what I see on your console.
Again, you are passing only the message to the Form component. You can pass both the message and id like so:

...
{messageText.map((data: any) => (
  <Form {...data} />
))}
...

Then in Form component, use it like so:

const Form = ({ id, message }) => {
...
}

Leave a Reply Cancel reply