How to pass array or object from JS to Rust for WebAssembly

257 views Asked by At

Is it possible to pass array (String array) or object from JS to Rust? This code compiles without errors, but does not work.

#[wasm_bindgen]
#[derive(Debug)]
pub struct Input {
    array: Vec<String>,
}

#[wasm_bindgen]
pub fn array_length(input: &Input) -> usize {
    input.array.len()
}

I also tried serde-wasm-bindgen, but still doesnt work.

WebAssembly does not expect to receive array or object from JS?

1

There are 1 answers

1
Erik On

You can use JsValue from wasm_bindgen to send arrays between JS and Rust.

pub fn rotate_cube_colors(cube_colors: JsValue, instructions: JsValue) -> JsValue { 
   let cube_colors: Result<[CubeColor; 27], serde_wasm_bindgen::Error> =
        serde_wasm_bindgen::from_value(cube_colors);
   
   // More logic goes here...

   let response = JsonResponse {
        error_message: None,
        data: Some(cube_colors),// cube_colors is an array
    };

    let json = serde_json::to_string(&response).unwrap();
    return JsValue::from_str(&json);
}

And then call it from React like:

export const rotateCubes = (
  prev: CubeColor[],
  rotation: {
    cube_index: number;
    axis: "X" | "Y" | "Z";
    direction: "Forwards" | "Backwards";
  }
) => JSON.parse(rotate_cube_colors(prev, [rotation])).data;

Full repo can be found here: https://github.com/eriktoger/rubiks_cube