skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    My solution:

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

    };


  2. 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 }) => {
    ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search