Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

empty text when trying to iterate JSON from axios in react

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:
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 }) => {
...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading