P5-wrapper / react

A wrapper component that allows you to utilise P5 sketches within React apps.
https://P5-wrapper.github.io/react/
MIT License
505 stars 50 forks source link

unexpected array behavior inside p5 sketch function #260

Closed TymonZ closed 1 year ago

TymonZ commented 1 year ago

I run into an issue when porting a cellular automaton I coded in standard p5.js to a Next.js project. I managed to isolate the bug that I suppose is responsible for the code not working. Here's the isolated issue:

My files

The contents of index.js

import Head from 'next/head'
import Issue from '@/components/p5/Issue'

export default function Home() {
  return (
    <>
      <Head>
        <title>++test++</title>
        <meta name="description" content="Generated by create next app" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
      </Head>
      <div className='w-screen h-screen relative'>
        <Issue />
      </div>
    </>
  )
}

The contents of issue.jsx

import React from "react";
import { NextReactP5Wrapper } from "@p5-wrapper/next";

const sketch = p5 => {
    let board
    let size = 10
    p5.setup = () => {
        p5.createCanvas(200, 200)
        board = new Array(size);
        for (let i = 0; i < size; i++) {
            board[i] = new Array(size);
        }
        cokurwa()
    }
    const cokurwa = () => {
        console.log('before for:', board)
        console.log('before for:', board[1][0])
        for (let i = 0; i < board.length; i++) {
            board[i][0] = i;
        }
        console.log('after for:', board)
        console.log('after for:', board[1][0])
        console.log('==================')
    }
}

const Issue = () => {
    return (
        <NextReactP5Wrapper sketch={sketch} />
    )
}

export default Issue

Expected Behavior

  1. the sketch function is executed once
  2. console.log('before for:', board) in cokurwa() outputs a 2d array where each element is undefined
  3. console.log('before for:', board[1][0]) in cokurwa() outputs undefined

Actual Behavior

image

  1. the sketch function is executed two times, instead of one
  2. console.log('before for:', board) seems to output contents of board after the for loop has executed
  3. console.log('before for:', board[1][0]) outputs undefined like it logically should

Steps to Reproduce the Problem

  1. Paste the code I attached in the "My files" section to a create-next-app setup

Specifications

Package Version: "@p5-wrapper/next": "^0.2.0"

TymonZ commented 1 year ago

moved the issue to P5-wrapper/next