1

I've stored the form data in an object and sending this data through props using addedUser(userData); I've send a POST request to the firebase and then fetching the data to display the user's details in JSX, my AddUserForm.js have form and data sending to App.js for sending POST request, So how can I add my UserCard immediately right after form submission?

For now I'm reloading the page as the form submits, but I don't think that's the right way, right?

const onFormSubmit = () => {
     addedUser(userData);
     window.location.reload(true);
}

And I did this in my App.js to fetch and sending post request to firebase

function App() {
    const [userData, setUserData] = useState([]);

    const fetchData = useCallback(async () => {
        try {
            const responseData = await fetch(
                "https://react-users-db-default-rtdb.asia-southeast1.firebasedatabase.app/users.json"
            );
            const data = await responseData.json();
            const loadedData = [];
            for (const key in data) {
                loadedData.push({
                    key: key,
                    userName: data[key].userName,
                    userEmail: data[key].userEmail,
                    userBio: data[key].userBio,
                    userGithub: data[key].userGithub,
                    userImage: data[key].userImage,
                });
            }
            setUserData(loadedData.reverse());
        } catch (err) {
            console.log(err);
        }
    }, []);

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

    async function recieveUserData(users) {
        const responseData = await fetch(
            "https://react-users-db-default-rtdb.asia-southeast1.firebasedatabase.app/users.json",
            {
                method: "POST",
                body: JSON.stringify(users),
                headers: {
                    "Content-Type": "application/json",
                },
            }
        );
        const data = await responseData.json();
        console.log(data);
    }

    return (
        <main>
            <div className="form__wrap">
                <AddUserForm addedUser={recieveUserData} />
            </div>
            <div className="user__wrap">
                {userData.length > 0 ? (
                    <Users newUser={userData} />
                ) : (
                    <p>No user found</p>
                )}
            </div>
        </main>
    );
}
5
  • There should be no full page reload in react / SPA's tbh ... you can pass the data to your component as props .. Commented Oct 2, 2022 at 7:01
  • yes, so how can I display the fetched data immediately? Commented Oct 2, 2022 at 7:02
  • you have to pass as props and it does render it when data is available ... you mean after the response arrives or the same data that is being sent to server ? Commented Oct 2, 2022 at 7:04
  • can you please show me through code example? Here is my updated repo code, you can check - github.com/mohitdevelops/user-entry/blob/main/src/App.js Commented Oct 2, 2022 at 7:06
  • I would personally use something like react query. It can simplify a lot of things, including what you're trying to achieve. Right after submitting the data, you could invalidate the original user fetch which would then re fetch it or just use some of the built in props like re fetch. Commented Oct 2, 2022 at 14:39

2 Answers 2

2

A sample, on how I would do the same

  • you can set the data coming from response if it is different from the data being sent and can also have a check if it has no error response from server too.

const { useState } = React;

const App = () => {
  const [data, setData] = useState(null);

  const submitHandler = () => {
    const fakeData = {
      userId: 1,
      id: 1,
      title: "sunt aut facere repellat provident oreprehenderit",
      body: "quia et suscipit\nsuscipit recusandae consequuntur",
    };
    fetch("https://jsonplaceholder.typicode.com/posts", {
      method: "POST",
      body: JSON.stringify(fakeData),
    })
      .then((response) => response.json())
      .then((json) => setData(fakeData));
  };

  return (
    <div>
      <button onClick={submitHandler}> fake post </button>
      <hr></hr>
      {data && <Cards title={data.title} body={data.title} />}
    </div>
  );
};

const Cards = ({ title, body }) => {
  return (
    <div>
      <h2>{title}</h2>
      <p>{body}</p>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

0

You can call fetchData at the bottom of recieveUserData function, just below the const data = await responseData.json(); statement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.