Connect to Database

We can use Axios for it, but nowadays we have a built-in mechanism for sending an HTTP request, that is Fetch API. 

Getting Data: 

    We don't use the function result directly b/c it is an async function and return a promise and the result data later.

    res => res.json(); => It is used to convert string to JSON format


    const [item, setItem] = useState();

    // Use effect is used to avoid unnecessary loading

    useEffect(() => {

        function fetchItemsHandler() {

        fetch(URL)

            .then(res => res.json())

            .then(data => {

                setItem(data.requiredParemeter);

            })

    }

    fetchItemHandler();

}, [])


OR


    We can directly use data too as:


        async function fetchItemsHandler() {

        const res = await fetch(URL)

        const data = await res.json()

       setItem(data.requiredParameter)

    }

    fetchItemHandler();


Sending Data: 

            fetch("https://e-commerce-cb57e-default-rtdb.firebaseio.com/cart.json", {
         method: "POST",
          body: JSON.stringify(newItem),
           headers: {
             "Content-type": "application/json; charset=UTF-8",
           },
          })
           .then((res) => res.json)
           .then((body) => {
             console.log(body);
           });

OR


        await fetch(
          "https://e-commerce-cb57e-default-rtdb.firebaseio.com/cart.json",
          {
            method: "POST",
            body: JSON.stringify(newItem),
            headers: {
              "Content-type": "application/json; charset=UTF-8",
            },
          }
        )

Comments