0

I am making a simple To Do list app using NEAR. I am a beginner in React. I have developed majority of it. One issue I am facing is that, my Note component only renders when there are two notes in the UseState array. Here is how I am rendering. When I console.log the elements, I can see the one element but it doesnt seem to render. Any suggestions on what I could be doing wrong?

//APP.JS File
 import 'regenerator-runtime/runtime'
import React, { useState } from 'react'
import './assets/css/global.css'
import { callSmartContractFunction, insertNote, viewBlockchainState, viewNotes } from './near-api'
import { EducationalText, NearInformation, SignInPrompt, SignOutButton } from './ui-components';
import Note from './Components/Note'
import CreateArea from './Components/CreateArea';

export default function App() {
  // Will store data returned from the blockchain in component state
  const [valueFromBlockchain, setValueFromBlockchain] = React.useState();
  const [notesBlock, setnotesBlock] = useState([]);
  const [uiPleaseWait, setUiPleaseWait] = React.useState(false);
  const [notesForUser, setNotesForUser] = useState([]);
  var setOfNotes = []

  // If user not signed-in with wallet - show prompt
  if (!window.walletConnection.isSignedIn()) {
    // Sign-in flow will reload the page later
    return SignInPrompt();
  } else {
    // Get blockchian state once on component load
    React.useEffect(() => {
      viewNotes()
        .then(val => setNotesForUser(val));
    }, []);
   
    
   
  }

  const updateMessage = (message) => {
    setUiPleaseWait(true);
    callSmartContractFunction(message).then(() =>
      {
        viewBlockchainState()
          .then(val => {
            setValueFromBlockchain(val);
            setUiPleaseWait(false);
          });
      });
  }

  function handleAdd(newNote) {
    
    console.log("CLicks come through")
    event.preventDefault();
  //   setnotesBlock(prevValue => {
  //     return[...prevValue, newNote
  //     ];
      
  // })
  console.log(newNote.content)
    //addToChain(newNote)
   // console.log(notesBlock)
    console.log("Just beforeaddToChain ")
    addToChain(newNote)
  


  }

  
  const addToChain = (newNote) => {
    setUiPleaseWait(true);
    insertNote(newNote).then(() =>
      {
        viewNotes()
          .then(val => {
            setNotesForUser(val);
            setUiPleaseWait(false);
          });
      });
  }

  function handleViewNotes() {
    console.log("CLicks come through for")
    event.preventDefault();

    //console.log(viewNotesOnChain());
    viewNotesOnChain()
   // setNotesForUser(setOfNotes);
   console.log("above value from blockchain");
    console.log(notesForUser);

  }

  
  const viewNotesOnChain = () => {
    setUiPleaseWait(true);
     viewNotes().then(() =>
      {
        viewNotes()
          .then(val => {
            setNotesForUser(val);
            setUiPleaseWait(false);
          });
      });
      
  }
  
  return (
    

    <>
      <SignOutButton/>
      
      <main className={uiPleaseWait && 'please-wait'}>
        <h1>{valueFromBlockchain}</h1>
        
        <div className='change'>
          <button onClick={() => updateMessage('Top of the Mornin!')}>
            Change greeting to<br/> <span>'Top of the Mornin!'</span>
          </button>
          <button onClick={() => updateMessage('Go Team!')}>
            Change greeting to<br/> <span>'Go Team!'</span>
          </button>
        </div>

        <NearInformation message={valueFromBlockchain}/>
        
        <EducationalText/>
        <p>Notes for User: </p> 
          
        <CreateArea onAdd = {handleAdd} />
       <button onClick={handleViewNotes}>View notes</button>
     
      
        { Array.isArray(notesForUser) && uiPleaseWait == false && notesForUser.map((noteItem, Index) => {
        return (<Note title={noteItem.title} content={noteItem.content} id = {Index} key ={Index} />);
       })
      }


    
      </main>
    </>
  )
}

Near api File below

//Near-API.js file - viewNotes and inserNotes are the relevant functions
    import { connect, keyStores, WalletConnection } from 'near-api-js'
import { parseNearAmount } from 'near-api-js/lib/utils/format'
import { getConfig } from './config'

const nearConfig = getConfig(process.env.NODE_ENV || 'development')

// Initialize contract and set global variables
export async function initContract() {
  // Initialize connection to the NEAR blockchain
  const near = await connect(Object.assign({ deps: { keyStore: new keyStores.BrowserLocalStorageKeyStore() } }, nearConfig));

  // Initializing Wallet based Account. It can work with NEAR testnet wallet that
  // is hosted at https://wallet.testnet.near.org
  window.walletConnection = new WalletConnection(near);

  // Getting the Account ID. If signed-out, it's empty string
  window.accountId = window.walletConnection.getAccountId();
}

export function signInWithNearWallet() {
  // Allow the current app to make calls to the specified contract on the
  // user's behalf.
  // This works by creating a new access key for the user's account and storing
  // the private key in localStorage.
  window.walletConnection.requestSignIn(nearConfig.contractName);
}

export function signOutNearWallet() {
  window.walletConnection.signOut();
  // reload page
  window.location.replace(window.location.origin + window.location.pathname);
}

/*
  Performs a view call to contract's `viewGreeting` method, to get data from the blockchain
*/
export async function viewBlockchainState() {
  let account = window.walletConnection.account();

  const currentState = await account.viewFunction(
    nearConfig.contractName,
    'viewGreeting',
    {},
  );

  return currentState;
}

/*
  Calls a contract method which will manipulate blockchain state.
*/
export async function callSmartContractFunction(messageArg) {
  let account = window.walletConnection.account();

  // Use near-api-js to perform a smart contract function call
  const result = await account.functionCall({
    contractId: nearConfig.contractName,
    methodName: 'setGreeting',
    args: {
      'message': messageArg
    },
    gas: '300000000000000',
  });

  return result;
}

export async function insertNote(note) {
  let account = window.walletConnection.account();

  // Use near-api-js to perform a smart contract function call
  const result = await account.functionCall({
    contractId: nearConfig.contractName,
    methodName: 'newNote',
    args: {
      'note': {"title":note.title, "content":note.content}
    },
    gas: '300000000000000',
  });
  near.log(note);
  console.log(note);
  return result;
}

export async function viewNotes() {
  let account = window.walletConnection.account();

  // Use near-api-js to perform a smart contract function call
  const result = await account.viewFunction(
    nearConfig.contractName,
    'viewNotes',
    {},
  );
  return result;
}
paddy
  • 123
  • 1
  • 2
  • 13
  • can you attach the source code of your smart contract with the methods `newNote` and `viewNotes`? – Max Nov 09 '22 at 12:59

0 Answers0