React Basics

React Lifecycle: Mounting, Updating, Unmounting

useEffect(() => { 
  console.log('Component has mounted'); 
  return (() => { 
    console.log("Component has unmounted");
  })
}, [])
  • If empty array is supplied, this useEffect() will only be trigger on mount
  • If it’s not supplied, useEffect() will be triggered on both mounting and updating whenever something is changed on the component
  • If a variable is supplied in the empty array, useEffect() will only be triggered when that variable changed
 

import Keyboards from './components/Keyboards'

function App() {

  return (
    <div className="App">
      <Keyboards />
    </div>
  );
}

export default App;
const Keyboard = ({keyboard}) => { 
    return (
        <div className="KeyboardCard">
            <strong>{keyboard.name}</strong>
            <div>{keyboard.msrp}</div>
        </div>
    )
}
export default Keyboard
import { useEffect, useState } from 'react'
import Keyboard from './Keyboard'

const Keyboards = () => { 
    const [keyboards, setKeyboards] = useState([]);

    const [name, setName] = useState([]);
    const [msrp, setMsrp] = useState([]);
    const [id, setId] = useState([]);
    const [isGood, setIsGood] = useState([]);
    const [videoId, setVideoId] = useState([]);


    useEffect(() => { 
        const getKeyboards = async() => { 
            const api = await fetch('http://localhost:5000/keyboards'); 
            const data = await api.json(); 
            setKeyboards(data);
        }
        getKeyboards()
    }, [])



    const onSubmit = async (e) => { 
        e.preventDefault();

        const resp = await fetch('http://localhost:5000/keyboards', { 
            method: 'POST', 
            headers: { 
                'Content-type': 'application/json'
            }, 
            body: JSON.stringify({name, msrp, id, isGood, videoId})
        }); 

        const data = await resp.json(); 
        setKeyboards([...keyboards, data])
    }

    return (
        <div>
            <form name="review" onSubmit={onSubmit}>
                Name: <input name="name" type="text" onChange={ e => setName(e.target.value) }/> <br />
                MSRP: <input name="msrp" type="text" onChange={e => setMsrp(e.target.value)} /> <br />
                ID: <input name="id" type="number" onChange={e => setId(e.target.value)}/> <br />
                isGood: <input name="isGood" type="checkbox" onChange={e => setIsGood(e.target.value)}/> <br/>
                Video Id: <input name="videoId" type="text" onChange={e => setVideoId(e.target.value)}/> <br/>
                <button>Add new review</button>
            </form>

            
            {  
                keyboards.map((keyboard) => (
                    <Keyboard key={keyboard.id} keyboard={keyboard} />
                ))
            }
        
        </div>
    )

}

export default Keyboards