DeveloperBreeze

Blockchain Development Programming Tutorials, Guides & Best Practices

Explore 30+ expertly crafted blockchain development tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.

Creating a Decentralized Application (dApp) with Solidity, Ethereum, and IPFS: From Smart Contracts to Front-End

Tutorial August 20, 2024
javascript solidity

import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import MyDapp from './contracts/MyDapp.json';

function Dapp() {
  const [message, setMessage] = useState('');
  const [newMessage, setNewMessage] = useState('');
  const [web3, setWeb3] = useState(null);
  const [contract, setContract] = useState(null);
  const [account, setAccount] = useState('');

  useEffect(() => {
    const init = async () => {
      const web3 = new Web3(Web3.givenProvider || 'http://localhost:7545');
      const networkId = await web3.eth.net.getId();
      const deployedNetwork = MyDapp.networks[networkId];
      const contractInstance = new web3.eth.Contract(
        MyDapp.abi,
        deployedNetwork && deployedNetwork.address,
      );
      const accounts = await web3.eth.getAccounts();
      setWeb3(web3);
      setContract(contractInstance);
      setAccount(accounts[0]);
      const initialMessage = await contractInstance.methods.getMessage().call();
      setMessage(initialMessage);
    };
    init();
  }, []);

  const updateMessage = async () => {
    await contract.methods.setMessage(newMessage).send({ from: account });
    const updatedMessage = await contract.methods.getMessage().call();
    setMessage(updatedMessage);
    setNewMessage('');
  };

  return (
    <div>
      <h1>Current Message: {message}</h1>
      <input
        type="text"
        value={newMessage}
        onChange={(e) => setNewMessage(e.target.value)}
      />
      <button onClick={updateMessage}>Update Message</button>
    </div>
  );
}

export default Dapp;

Navigate to the client directory and start the React application: