Home > front end >  Passing a String[] from react to springboot
Passing a String[] from react to springboot

Time:12-31

I want to pass a String array of usernames from react to Spring so that I can then get some user details for each of those usernames and finally pass this back to react as a List<String>

So far in react, I am making an array of usernames, and then passing them as the request body to spring

        const roundRobin = () => {
        const userList = []
        //Get list of entrants usernames to pass to backend
        for(let i =  0; i < entrants.length; i  ){
          userList.push(entrants[i].username);
          console.log(userList);
        }
        const List = JSON.stringify(userList) 

        //API call
        apiCalls
        .getRandomUserList(List)
        .then((response) => {
          console.log(response.data);
        })
        .catch((apiError) => {
          if (apiError.response.data && apiError.response.data.validationErrors) {
            setEditErrors(apiError.response.data.validationErrors);
          }
          console.log(apiError.response.data)
          setPendingApiCall(false);
        });
        
      }

In spring my controller takes the request body as a String[]

//create a random list of members who have entered an event
    @CrossOrigin
    @GetMapping("/users/createRandomList")
    List<String> randomList(@RequestBody String[] usernames) {
        return userService.createRandomUserList(usernames);
    }

The UserService then takes the String[] and changes it to a List and calls a method which randomly rearranges the order of the Strings, it then loops through the returned List (which are a username) and gets the User from the database and adds some details about that User to a new List This is then returned to react.

public List<String> createRandomUserList(String[] randomUsernames) {
        List<String> users = new ArrayList<>();
        List<String> randomUsersList = Arrays.asList(randomUsernames);
        List<String> randomUsers = getRandomUsers(randomUsersList);
        for (String randUsernames : randomUsers) {
            User u = userRepository.findByUsername(randUsernames);
            users.add(u.getFirstname()   " "   u.getSurname()   " "   u.getHandicap());
        }
        return users;

    }

    //Create list of entrants IDs in random order for tee times.
    public List<String> getRandomUsers(List<String> userIds) {
        int size = userIds.size();
        List<String> passedList = userIds;
        List<String> entrants = new ArrayList<>();
        Random rand = new Random();
        for(int i = 0; i < size; i  ) {
            int randomIndex = rand.nextInt(passedList.size());
            entrants.add(passedList.get(randomIndex));
            passedList.remove(randomIndex);
        }
        return entrants;
    }

When I try and run this in my web app though, I get an HTTP 400 error,

{timestamp: 1640902047907, status: 400, message: 'Required request body is missing: java.util.List<j…ser.UserController.randomList(java.lang.String[])', url: '/api/1.0/users/createRandomList'}

I am not sure what I am doing wrong, as far as I can tell, I am passing an array to Spring, when I console.log(List), I get ["user1","user2"]

CodePudding user response:

I think you should change the get mapping to post mapping and then use the List instead of String[], try in that way

@CrossOrigin
    @GetMapping("/users/createRandomList")
    List<String> randomList(@RequestBody List<String> usernames) {
        return userService.createRandomUserList(usernames);
}

also change service methods according to the changes

  • Related