menu

Questions & Answers

SET function not working for realtime database using firebase v9 in REACT?

I was wondering how to send and get the data from realtime database in react.js using firebase v9? I tried to send it and this way works on vanilla js but for some reason it doesnt work in react... can you please help me?

Here is the code i have:

function firebase() {

  const firebaseConfig = {
    apiKey: "AIzaSyBSfCRuSd00AU4HE3ZhKatj9Tgp7aKEhUE",
    authDomain: "credit-cards-3facb.firebaseapp.com",
    projectId: "credit-cards-3facb",
    storageBucket: "credit-cards-3facb.appspot.com",
    messagingSenderId: "143333603416",
    appId: "1:143333603416:web:42ba9616a7dcc2f26db22d"
  };
  
  const app = initializeApp(firebaseConfig);
  const db = getDatabase(app);

  const [state, setState] = useState({
    name: "",
    oib: "",
    birthYear: ""
  });

  const sendData = (e) => {
    e.preventDefault();
    console.log(state);
    set(ref(db, "Users/" + state.name), { // WHOLE CODE BLOCK IS NOT WORKING
      ime: state.name,
      oib: state.oib,
      godina_rodenja: state.birthYear
    })
    .then(() => alert("success"))
    .catch(error => console.error(error));
  }

  useEffect(() => {
    // HOW TO GET DATA FROM REALTIME DATABASE
  }, []);
 
}

JSX:

    <div>
      <form onSubmit={sendData}>
        <span>Ime:</span>
        <input type="text" name="name" id="name" value={state.name} onChange={handleChange} /><br />
        <span>Broj:</span>
        <input type="number" name="oib" id="oib" maxLength="12" value={state.oib} onChange={handleChange} /><br />
        <span>Godina rođenja:</span>
        <input type="number" name="birthYear" id="birthYear" value={state.birthYear} onChange={handleChange} /><br /><br />
        <input type="submit" value="Send" />
      </form>
    </div>
Comments:
2023-01-18 23:25:06
What does your console.log(state); output?
2023-01-18 23:25:06
On "// HOW TO GET DATA FROM REALTIME DATABASE". Did you try anything yet? There are lots of existing questions showing what others have tried, and probably some good tutorials here too: google.com/search?q=reactjs+usestate+firebase+realtime+datab‌​ase. If something you find is for the v8 API, you can read the upgrade guide to learn how to update it.
2023-01-18 23:25:06
@FrankvanPuffelen it outputs the values i typed in the form
Answers(0) :